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.

69894 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 54
  52. #define JUCE_BUILDNUMBER 7
  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. /** JUCE_FORCE_DEBUG: Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and
  191. project settings, but if you define this value, you can override this to force
  192. it to be true or false.
  193. */
  194. #ifndef JUCE_FORCE_DEBUG
  195. //#define JUCE_FORCE_DEBUG 0
  196. #endif
  197. /** JUCE_LOG_ASSERTIONS: If this flag is enabled, the the jassert and jassertfalse
  198. macros will always use Logger::writeToLog() to write a message when an assertion happens.
  199. Enabling it will also leave this turned on in release builds. When it's disabled,
  200. however, the jassert and jassertfalse macros will not be compiled in a
  201. release build.
  202. @see jassert, jassertfalse, Logger
  203. */
  204. #ifndef JUCE_LOG_ASSERTIONS
  205. #define JUCE_LOG_ASSERTIONS 0
  206. #endif
  207. /** JUCE_ASIO: Enables ASIO audio devices (MS Windows only).
  208. Turning this on means that you'll need to have the Steinberg ASIO SDK installed
  209. on your Windows build machine.
  210. See the comments in the ASIOAudioIODevice class's header file for more
  211. info about this.
  212. */
  213. #ifndef JUCE_ASIO
  214. #define JUCE_ASIO 0
  215. #endif
  216. /** JUCE_WASAPI: Enables WASAPI audio devices (Windows Vista and above).
  217. */
  218. #ifndef JUCE_WASAPI
  219. #define JUCE_WASAPI 0
  220. #endif
  221. /** JUCE_DIRECTSOUND: Enables DirectSound audio (MS Windows only).
  222. */
  223. #ifndef JUCE_DIRECTSOUND
  224. #define JUCE_DIRECTSOUND 1
  225. #endif
  226. /** JUCE_DIRECTSHOW: Enables DirectShow media-streaming architecture (MS Windows only).
  227. */
  228. #ifndef JUCE_DIRECTSHOW
  229. #define JUCE_DIRECTSHOW 0
  230. #endif
  231. /** JUCE_MEDIAFOUNDATION: Enables Media Foundation multimedia platform (Windows Vista and above).
  232. */
  233. #ifndef JUCE_MEDIAFOUNDATION
  234. #define JUCE_MEDIAFOUNDATION 0
  235. #endif
  236. #if ! JUCE_WINDOWS
  237. #undef JUCE_DIRECTSHOW
  238. #undef JUCE_MEDIAFOUNDATION
  239. #endif
  240. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  241. #ifndef JUCE_ALSA
  242. #define JUCE_ALSA 1
  243. #endif
  244. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  245. #ifndef JUCE_JACK
  246. #define JUCE_JACK 0
  247. #endif
  248. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  249. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  250. installed, and its header files will need to be on your include path.
  251. */
  252. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IOS || JUCE_ANDROID || (JUCE_WINDOWS && ! JUCE_MSVC))
  253. #define JUCE_QUICKTIME 0
  254. #endif
  255. #if (JUCE_IOS || JUCE_LINUX) && JUCE_QUICKTIME
  256. #undef JUCE_QUICKTIME
  257. #endif
  258. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  259. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  260. */
  261. #if ! (defined (JUCE_OPENGL) || JUCE_ANDROID)
  262. #define JUCE_OPENGL 1
  263. #endif
  264. /** JUCE_DIRECT2D: Enables the Windows 7 Direct2D renderer.
  265. If you're building on a platform older than Vista, you won't be able to compile with this feature.
  266. */
  267. #ifndef JUCE_DIRECT2D
  268. #define JUCE_DIRECT2D 0
  269. #endif
  270. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  271. If your app doesn't need to read FLAC files, you might want to disable this to
  272. reduce the size of your codebase and build time.
  273. */
  274. #ifndef JUCE_USE_FLAC
  275. #define JUCE_USE_FLAC 1
  276. #endif
  277. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  278. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  279. reduce the size of your codebase and build time.
  280. */
  281. #ifndef JUCE_USE_OGGVORBIS
  282. #define JUCE_USE_OGGVORBIS 1
  283. #endif
  284. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  285. Unless you're using CD-burning, you should probably turn this flag off to
  286. reduce code size.
  287. */
  288. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  289. #define JUCE_USE_CDBURNER 1
  290. #endif
  291. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  292. Unless you're using CD-reading, you should probably turn this flag off to
  293. reduce code size.
  294. */
  295. #ifndef JUCE_USE_CDREADER
  296. #define JUCE_USE_CDREADER 1
  297. #endif
  298. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  299. */
  300. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  301. #define JUCE_USE_CAMERA 0
  302. #endif
  303. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  304. gets repainted will flash in a random colour, so that you can check exactly how much and how
  305. often your components are being drawn.
  306. */
  307. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  308. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  309. #endif
  310. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  311. Unless you specifically want to disable this, it's best to leave this option turned on.
  312. */
  313. #ifndef JUCE_USE_XINERAMA
  314. #define JUCE_USE_XINERAMA 1
  315. #endif
  316. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  317. turned on unless you have a good reason to disable it.
  318. */
  319. #ifndef JUCE_USE_XSHM
  320. #define JUCE_USE_XSHM 1
  321. #endif
  322. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  323. */
  324. #ifndef JUCE_USE_XRENDER
  325. #define JUCE_USE_XRENDER 0
  326. #endif
  327. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  328. unless you have a good reason to disable it.
  329. */
  330. #ifndef JUCE_USE_XCURSOR
  331. #define JUCE_USE_XCURSOR 1
  332. #endif
  333. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  334. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  335. you're building a plugin hosting app.
  336. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  337. */
  338. #ifndef JUCE_PLUGINHOST_VST
  339. #define JUCE_PLUGINHOST_VST 0
  340. #endif
  341. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  342. of course, and should only be enabled if you're building a plugin hosting app.
  343. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  344. */
  345. #ifndef JUCE_PLUGINHOST_AU
  346. #define JUCE_PLUGINHOST_AU 0
  347. #endif
  348. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  349. This should be enabled if you're writing a console application.
  350. */
  351. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  352. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  353. #endif
  354. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  355. If you're not using any embedded web-pages, turning this off may reduce your code size.
  356. */
  357. #ifndef JUCE_WEB_BROWSER
  358. #define JUCE_WEB_BROWSER 1
  359. #endif
  360. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  361. Carbon isn't required for a normal app, but may be needed by specialised classes like
  362. plugin-hosts, which support older APIs.
  363. */
  364. #if ! (defined (JUCE_SUPPORT_CARBON) || defined (__LP64__))
  365. #define JUCE_SUPPORT_CARBON 1
  366. #endif
  367. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  368. You might need to tweak this if you're linking to an external zlib library in your app,
  369. but for normal apps, this option should be left alone.
  370. */
  371. #ifndef JUCE_INCLUDE_ZLIB_CODE
  372. #define JUCE_INCLUDE_ZLIB_CODE 1
  373. #endif
  374. #ifndef JUCE_INCLUDE_FLAC_CODE
  375. #define JUCE_INCLUDE_FLAC_CODE 1
  376. #endif
  377. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  378. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  379. #endif
  380. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  381. #define JUCE_INCLUDE_PNGLIB_CODE 1
  382. #endif
  383. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  384. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  385. #endif
  386. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check for certain objects when
  387. the app terminates. See the LeakedObjectDetector class and the JUCE_LEAK_DETECTOR
  388. macro for more details about enabling leak checking for specific classes.
  389. */
  390. #if JUCE_DEBUG && ! defined (JUCE_CHECK_MEMORY_LEAKS)
  391. #define JUCE_CHECK_MEMORY_LEAKS 1
  392. #endif
  393. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  394. that are thrown by the message dispatch loop. With it enabled, any unhandled exceptions
  395. are passed to the JUCEApplication::unhandledException() callback for logging.
  396. */
  397. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  398. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  399. #endif
  400. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  401. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  402. #undef JUCE_QUICKTIME
  403. #define JUCE_QUICKTIME 0
  404. #undef JUCE_OPENGL
  405. #define JUCE_OPENGL 0
  406. #undef JUCE_USE_CDBURNER
  407. #define JUCE_USE_CDBURNER 0
  408. #undef JUCE_USE_CDREADER
  409. #define JUCE_USE_CDREADER 0
  410. #undef JUCE_WEB_BROWSER
  411. #define JUCE_WEB_BROWSER 0
  412. #undef JUCE_PLUGINHOST_AU
  413. #define JUCE_PLUGINHOST_AU 0
  414. #undef JUCE_PLUGINHOST_VST
  415. #define JUCE_PLUGINHOST_VST 0
  416. #endif
  417. #endif
  418. /*** End of inlined file: juce_Config.h ***/
  419. #ifndef JUCE_NAMESPACE
  420. #define JUCE_NAMESPACE juce
  421. #endif
  422. #define BEGIN_JUCE_NAMESPACE namespace JUCE_NAMESPACE {
  423. #define END_JUCE_NAMESPACE }
  424. /*** Start of inlined file: juce_PlatformDefs.h ***/
  425. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  426. #define __JUCE_PLATFORMDEFS_JUCEHEADER__
  427. /* This file defines miscellaneous macros for debugging, assertions, etc.
  428. */
  429. #ifdef JUCE_FORCE_DEBUG
  430. #undef JUCE_DEBUG
  431. #if JUCE_FORCE_DEBUG
  432. #define JUCE_DEBUG 1
  433. #endif
  434. #endif
  435. /** This macro defines the C calling convention used as the standard for Juce calls. */
  436. #if JUCE_MSVC
  437. #define JUCE_CALLTYPE __stdcall
  438. #define JUCE_CDECL __cdecl
  439. #else
  440. #define JUCE_CALLTYPE
  441. #define JUCE_CDECL
  442. #endif
  443. // Debugging and assertion macros
  444. // (For info about JUCE_LOG_ASSERTIONS, have a look in juce_Config.h)
  445. #if JUCE_LOG_ASSERTIONS
  446. #define juce_LogCurrentAssertion juce_LogAssertion (__FILE__, __LINE__);
  447. #elif JUCE_DEBUG
  448. #define juce_LogCurrentAssertion std::cerr << "JUCE Assertion failure in " << __FILE__ << ", line " << __LINE__ << std::endl;
  449. #else
  450. #define juce_LogCurrentAssertion
  451. #endif
  452. #if JUCE_MAC || DOXYGEN
  453. /** This will try to break into the debugger if the app is currently being debugged.
  454. If called by an app that's not being debugged, the behaiour isn't defined - it may crash or not, depending
  455. on the platform.
  456. @see jassert()
  457. */
  458. #define juce_breakDebugger { Debugger(); }
  459. #elif JUCE_IOS || JUCE_LINUX || JUCE_ANDROID
  460. #define juce_breakDebugger { kill (0, SIGTRAP); }
  461. #elif JUCE_USE_INTRINSICS
  462. #ifndef __INTEL_COMPILER
  463. #pragma intrinsic (__debugbreak)
  464. #endif
  465. #define juce_breakDebugger { __debugbreak(); }
  466. #elif JUCE_GCC
  467. #define juce_breakDebugger { asm("int $3"); }
  468. #else
  469. #define juce_breakDebugger { __asm int 3 }
  470. #endif
  471. #if JUCE_DEBUG || DOXYGEN
  472. /** Writes a string to the standard error stream.
  473. This is only compiled in a debug build.
  474. @see Logger::outputDebugString
  475. */
  476. #define DBG(dbgtext) { JUCE_NAMESPACE::String tempDbgBuf; tempDbgBuf << dbgtext; JUCE_NAMESPACE::Logger::outputDebugString (tempDbgBuf); }
  477. /** This will always cause an assertion failure.
  478. It is only compiled in a debug build, (unless JUCE_LOG_ASSERTIONS is enabled for your build).
  479. @see jassert
  480. */
  481. #define jassertfalse { juce_LogCurrentAssertion; if (JUCE_NAMESPACE::juce_isRunningUnderDebugger()) juce_breakDebugger; }
  482. /** Platform-independent assertion macro.
  483. This macro gets turned into a no-op when you're building with debugging turned off, so be
  484. careful that the expression you pass to it doesn't perform any actions that are vital for the
  485. correct behaviour of your program!
  486. @see jassertfalse
  487. */
  488. #define jassert(expression) { if (! (expression)) jassertfalse; }
  489. #else
  490. // If debugging is disabled, these dummy debug and assertion macros are used..
  491. #define DBG(dbgtext)
  492. #define jassertfalse { juce_LogCurrentAssertion }
  493. #if JUCE_LOG_ASSERTIONS
  494. #define jassert(expression) { if (! (expression)) jassertfalse; }
  495. #else
  496. #define jassert(a) {}
  497. #endif
  498. #endif
  499. #ifndef DOXYGEN
  500. BEGIN_JUCE_NAMESPACE
  501. template <bool b> struct JuceStaticAssert;
  502. template <> struct JuceStaticAssert <true> { static void dummy() {} };
  503. END_JUCE_NAMESPACE
  504. #endif
  505. /** A compile-time assertion macro.
  506. If the expression parameter is false, the macro will cause a compile error. (The actual error
  507. message that the compiler generates may be completely bizarre and seem to have no relation to
  508. the place where you put the static_assert though!)
  509. */
  510. #define static_jassert(expression) JUCE_NAMESPACE::JuceStaticAssert<expression>::dummy();
  511. /** This is a shorthand macro for declaring stubs for a class's copy constructor and operator=.
  512. For example, instead of
  513. @code
  514. class MyClass
  515. {
  516. etc..
  517. private:
  518. MyClass (const MyClass&);
  519. MyClass& operator= (const MyClass&);
  520. };@endcode
  521. ..you can just write:
  522. @code
  523. class MyClass
  524. {
  525. etc..
  526. private:
  527. JUCE_DECLARE_NON_COPYABLE (MyClass);
  528. };@endcode
  529. */
  530. #define JUCE_DECLARE_NON_COPYABLE(className) \
  531. className (const className&);\
  532. className& operator= (const className&)
  533. /** This is a shorthand way of writing both a JUCE_DECLARE_NON_COPYABLE and
  534. JUCE_LEAK_DETECTOR macro for a class.
  535. */
  536. #define JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(className) \
  537. JUCE_DECLARE_NON_COPYABLE(className);\
  538. JUCE_LEAK_DETECTOR(className)
  539. #if ! DOXYGEN
  540. #define JUCE_JOIN_MACRO_HELPER(a, b) a ## b
  541. #endif
  542. /** A good old-fashioned C macro concatenation helper.
  543. This combines two items (which may themselves be macros) into a single string,
  544. avoiding the pitfalls of the ## macro operator.
  545. */
  546. #define JUCE_JOIN_MACRO(a, b) JUCE_JOIN_MACRO_HELPER (a, b)
  547. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  548. #define JUCE_TRY try
  549. #define JUCE_CATCH_ALL catch (...) {}
  550. #define JUCE_CATCH_ALL_ASSERT catch (...) { jassertfalse; }
  551. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  552. #define JUCE_CATCH_EXCEPTION JUCE_CATCH_ALL
  553. #else
  554. /** Used in try-catch blocks, this macro will send exceptions to the JUCEApplication
  555. object so they can be logged by the application if it wants to.
  556. */
  557. #define JUCE_CATCH_EXCEPTION \
  558. catch (const std::exception& e) \
  559. { \
  560. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__); \
  561. } \
  562. catch (...) \
  563. { \
  564. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__); \
  565. }
  566. #endif
  567. #else
  568. #define JUCE_TRY
  569. #define JUCE_CATCH_EXCEPTION
  570. #define JUCE_CATCH_ALL
  571. #define JUCE_CATCH_ALL_ASSERT
  572. #endif
  573. #if JUCE_DEBUG || DOXYGEN
  574. /** A platform-independent way of forcing an inline function.
  575. Use the syntax: @code
  576. forcedinline void myfunction (int x)
  577. @endcode
  578. */
  579. #define forcedinline inline
  580. #else
  581. #if JUCE_MSVC
  582. #define forcedinline __forceinline
  583. #else
  584. #define forcedinline inline __attribute__((always_inline))
  585. #endif
  586. #endif
  587. #if JUCE_MSVC || DOXYGEN
  588. /** This can be placed before a stack or member variable declaration to tell the compiler
  589. to align it to the specified number of bytes. */
  590. #define JUCE_ALIGN(bytes) __declspec (align (bytes))
  591. #else
  592. #define JUCE_ALIGN(bytes) __attribute__ ((aligned (bytes)))
  593. #endif
  594. // Cross-compiler deprecation macros..
  595. #if DOXYGEN || (JUCE_MSVC && ! JUCE_NO_DEPRECATION_WARNINGS)
  596. /** This can be used to wrap a function which has been deprecated. */
  597. #define JUCE_DEPRECATED(functionDef) __declspec(deprecated) functionDef
  598. #elif JUCE_GCC && ! JUCE_NO_DEPRECATION_WARNINGS
  599. #define JUCE_DEPRECATED(functionDef) functionDef __attribute__ ((deprecated))
  600. #else
  601. #define JUCE_DEPRECATED(functionDef) functionDef
  602. #endif
  603. #if JUCE_ANDROID && ! DOXYGEN
  604. #define JUCE_MODAL_LOOPS_PERMITTED 0
  605. #else
  606. /** Some operating environments don't provide a modal loop mechanism, so this flag can be
  607. used to disable any functions that try to run a modal loop. */
  608. #define JUCE_MODAL_LOOPS_PERMITTED 1
  609. #endif
  610. // Here, we'll check for C++2011 compiler support, and if it's not available, define
  611. // a few workarounds, so that we can still use a few of the newer language features.
  612. #if defined (__GXX_EXPERIMENTAL_CXX0X__) && defined (__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
  613. #define JUCE_COMPILER_SUPPORTS_CXX2011 1
  614. #endif
  615. #if defined (__clang__) && defined (__has_feature)
  616. #if __has_feature (cxx_noexcept) // (NB: do not add this test to the previous line)
  617. #define JUCE_COMPILER_SUPPORTS_CXX2011 1
  618. #endif
  619. #endif
  620. #if defined (_MSC_VER) && _MSC_VER >= 1600
  621. //#define JUCE_COMPILER_SUPPORTS_CXX2011 1
  622. #endif
  623. #if ! (DOXYGEN || JUCE_COMPILER_SUPPORTS_CXX2011)
  624. #define noexcept throw() // for c++98 compilers, we can fake these newer language features.
  625. #define nullptr (0)
  626. #endif
  627. #endif // __JUCE_PLATFORMDEFS_JUCEHEADER__
  628. /*** End of inlined file: juce_PlatformDefs.h ***/
  629. // Now we'll include any OS headers we need.. (at this point we are outside the Juce namespace).
  630. #if JUCE_MSVC
  631. #if JUCE_VC6
  632. #pragma warning (disable: 4284 4786) // (spurious VC6 warnings)
  633. namespace std // VC6 doesn't have sqrt/sin/cos/tan/abs in std, so declare them here:
  634. {
  635. template <typename Type> Type abs (Type a) { if (a < 0) return -a; return a; }
  636. template <typename Type> Type tan (Type a) { return static_cast<Type> (::tan (static_cast<double> (a))); }
  637. template <typename Type> Type sin (Type a) { return static_cast<Type> (::sin (static_cast<double> (a))); }
  638. template <typename Type> Type cos (Type a) { return static_cast<Type> (::cos (static_cast<double> (a))); }
  639. template <typename Type> Type sqrt (Type a) { return static_cast<Type> (::sqrt (static_cast<double> (a))); }
  640. template <typename Type> Type floor (Type a) { return static_cast<Type> (::floor (static_cast<double> (a))); }
  641. template <typename Type> Type ceil (Type a) { return static_cast<Type> (::ceil (static_cast<double> (a))); }
  642. template <typename Type> Type atan2 (Type a, Type b) { return static_cast<Type> (::atan2 (static_cast<double> (a), static_cast<double> (b))); }
  643. }
  644. #endif
  645. #pragma warning (push)
  646. #pragma warning (disable: 4514 4245 4100)
  647. #endif
  648. #include <cstdlib>
  649. #include <cstdarg>
  650. #include <climits>
  651. #include <limits>
  652. #include <cmath>
  653. #include <cwchar>
  654. #include <stdexcept>
  655. #include <typeinfo>
  656. #include <cstring>
  657. #include <cstdio>
  658. #include <iostream>
  659. #include <vector>
  660. #if JUCE_USE_INTRINSICS
  661. #include <intrin.h>
  662. #endif
  663. #if JUCE_MAC || JUCE_IOS
  664. #include <libkern/OSAtomic.h>
  665. #endif
  666. #if JUCE_LINUX
  667. #include <signal.h>
  668. #if __INTEL_COMPILER
  669. #if __ia64__
  670. #include <ia64intrin.h>
  671. #else
  672. #include <ia32intrin.h>
  673. #endif
  674. #endif
  675. #endif
  676. #if JUCE_MSVC && JUCE_DEBUG
  677. #include <crtdbg.h>
  678. #endif
  679. #if JUCE_MSVC
  680. #include <malloc.h>
  681. #pragma warning (pop)
  682. #if ! JUCE_PUBLIC_INCLUDES
  683. #pragma warning (4: 4511 4512 4100) // (enable some warnings that are turned off in VC8)
  684. #endif
  685. #endif
  686. #if JUCE_ANDROID
  687. #include <sys/atomics.h>
  688. #include <byteswap.h>
  689. #endif
  690. // DLL building settings on Win32
  691. #if JUCE_MSVC
  692. #ifdef JUCE_DLL_BUILD
  693. #define JUCE_API __declspec (dllexport)
  694. #pragma warning (disable: 4251)
  695. #elif defined (JUCE_DLL)
  696. #define JUCE_API __declspec (dllimport)
  697. #pragma warning (disable: 4251)
  698. #endif
  699. #ifdef __INTEL_COMPILER
  700. #pragma warning (disable: 1125) // (virtual override warning)
  701. #endif
  702. #elif defined (__GNUC__) && ((__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
  703. #ifdef JUCE_DLL_BUILD
  704. #define JUCE_API __attribute__ ((visibility("default")))
  705. #endif
  706. #endif
  707. #ifndef JUCE_API
  708. /** This macro is added to all juce public class declarations. */
  709. #define JUCE_API
  710. #endif
  711. /** This macro is added to all juce public function declarations. */
  712. #define JUCE_PUBLIC_FUNCTION JUCE_API JUCE_CALLTYPE
  713. /** This turns on some non-essential bits of code that should prevent old code from compiling
  714. in cases where method signatures have changed, etc.
  715. */
  716. #if (! defined (JUCE_CATCH_DEPRECATED_CODE_MISUSE)) && JUCE_DEBUG && ! DOXYGEN
  717. #define JUCE_CATCH_DEPRECATED_CODE_MISUSE 1
  718. #endif
  719. // Now include some basics that are needed by most of the Juce classes...
  720. BEGIN_JUCE_NAMESPACE
  721. extern JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger();
  722. #if JUCE_LOG_ASSERTIONS
  723. extern JUCE_API void juce_LogAssertion (const char* filename, int lineNum) noexcept;
  724. #endif
  725. /*** Start of inlined file: juce_Memory.h ***/
  726. #ifndef __JUCE_MEMORY_JUCEHEADER__
  727. #define __JUCE_MEMORY_JUCEHEADER__
  728. #if JUCE_MSVC || DOXYGEN
  729. /** This is a compiler-independent way of declaring a variable as being thread-local.
  730. E.g.
  731. @code
  732. juce_ThreadLocal int myVariable;
  733. @endcode
  734. */
  735. #define juce_ThreadLocal __declspec(thread)
  736. #else
  737. #define juce_ThreadLocal __thread
  738. #endif
  739. #if JUCE_MINGW
  740. /** This allocator is not defined in mingw gcc. */
  741. #define alloca __builtin_alloca
  742. #endif
  743. /** Fills a block of memory with zeros. */
  744. inline void zeromem (void* memory, size_t numBytes) noexcept { memset (memory, 0, numBytes); }
  745. /** Overwrites a structure or object with zeros. */
  746. template <typename Type>
  747. inline void zerostruct (Type& structure) noexcept { memset (&structure, 0, sizeof (structure)); }
  748. /** Delete an object pointer, and sets the pointer to null.
  749. Remember that it's not good c++ practice to use delete directly - always try to use a ScopedPointer
  750. or other automatic lieftime-management system rather than resorting to deleting raw pointers!
  751. */
  752. template <typename Type>
  753. inline void deleteAndZero (Type& pointer) { delete pointer; pointer = nullptr; }
  754. /** A handy function which adds a number of bytes to any type of pointer and returns the result.
  755. This can be useful to avoid casting pointers to a char* and back when you want to move them by
  756. a specific number of bytes,
  757. */
  758. template <typename Type>
  759. inline Type* addBytesToPointer (Type* pointer, int bytes) noexcept { return (Type*) (((char*) pointer) + bytes); }
  760. /** A handy function which returns the difference between any two pointers, in bytes.
  761. The address of the second pointer is subtracted from the first, and the difference in bytes is returned.
  762. */
  763. template <typename Type1, typename Type2>
  764. inline int getAddressDifference (Type1* pointer1, Type2* pointer2) noexcept { return (int) (((const char*) pointer1) - (const char*) pointer2); }
  765. /* In a win32 DLL build, we'll expose some malloc/free functions that live inside the DLL, and use these for
  766. allocating all the objects - that way all juce objects in the DLL and in the host will live in the same heap,
  767. avoiding problems when an object is created in one module and passed across to another where it is deleted.
  768. By piggy-backing on the JUCE_LEAK_DETECTOR macro, these allocators can be injected into most juce classes.
  769. */
  770. #if JUCE_MSVC && defined (JUCE_DLL) && ! DOXYGEN
  771. extern JUCE_API void* juceDLL_malloc (size_t);
  772. extern JUCE_API void juceDLL_free (void*);
  773. #define JUCE_LEAK_DETECTOR(OwnerClass) public:\
  774. static void* operator new (size_t sz) { return JUCE_NAMESPACE::juceDLL_malloc ((int) sz); } \
  775. static void* operator new (size_t, void* p) { return p; } \
  776. static void operator delete (void* p) { JUCE_NAMESPACE::juceDLL_free (p); } \
  777. static void operator delete (void*, void*) {}
  778. #endif
  779. /** (Deprecated) This was a win32-specific way of checking for object leaks - now please
  780. use the JUCE_LEAK_DETECTOR instead.
  781. */
  782. #ifndef juce_UseDebuggingNewOperator
  783. #define juce_UseDebuggingNewOperator
  784. #endif
  785. #endif // __JUCE_MEMORY_JUCEHEADER__
  786. /*** End of inlined file: juce_Memory.h ***/
  787. /*** Start of inlined file: juce_MathsFunctions.h ***/
  788. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  789. #define __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  790. /*
  791. This file sets up some handy mathematical typdefs and functions.
  792. */
  793. // Definitions for the int8, int16, int32, int64 and pointer_sized_int types.
  794. /** A platform-independent 8-bit signed integer type. */
  795. typedef signed char int8;
  796. /** A platform-independent 8-bit unsigned integer type. */
  797. typedef unsigned char uint8;
  798. /** A platform-independent 16-bit signed integer type. */
  799. typedef signed short int16;
  800. /** A platform-independent 16-bit unsigned integer type. */
  801. typedef unsigned short uint16;
  802. /** A platform-independent 32-bit signed integer type. */
  803. typedef signed int int32;
  804. /** A platform-independent 32-bit unsigned integer type. */
  805. typedef unsigned int uint32;
  806. #if JUCE_MSVC
  807. /** A platform-independent 64-bit integer type. */
  808. typedef __int64 int64;
  809. /** A platform-independent 64-bit unsigned integer type. */
  810. typedef unsigned __int64 uint64;
  811. /** A platform-independent macro for writing 64-bit literals, needed because
  812. different compilers have different syntaxes for this.
  813. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  814. GCC, or 0x1000000000 for MSVC.
  815. */
  816. #define literal64bit(longLiteral) ((__int64) longLiteral)
  817. #else
  818. /** A platform-independent 64-bit integer type. */
  819. typedef long long int64;
  820. /** A platform-independent 64-bit unsigned integer type. */
  821. typedef unsigned long long uint64;
  822. /** A platform-independent macro for writing 64-bit literals, needed because
  823. different compilers have different syntaxes for this.
  824. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  825. GCC, or 0x1000000000 for MSVC.
  826. */
  827. #define literal64bit(longLiteral) (longLiteral##LL)
  828. #endif
  829. #if JUCE_64BIT
  830. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  831. typedef int64 pointer_sized_int;
  832. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  833. typedef uint64 pointer_sized_uint;
  834. #elif JUCE_MSVC && ! JUCE_VC6
  835. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  836. typedef _W64 int pointer_sized_int;
  837. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  838. typedef _W64 unsigned int pointer_sized_uint;
  839. #else
  840. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  841. typedef int pointer_sized_int;
  842. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  843. typedef unsigned int pointer_sized_uint;
  844. #endif
  845. // Some indispensible min/max functions
  846. /** Returns the larger of two values. */
  847. template <typename Type>
  848. inline Type jmax (const Type a, const Type b) { return (a < b) ? b : a; }
  849. /** Returns the larger of three values. */
  850. template <typename Type>
  851. inline Type jmax (const Type a, const Type b, const Type c) { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  852. /** Returns the larger of four values. */
  853. template <typename Type>
  854. inline Type jmax (const Type a, const Type b, const Type c, const Type d) { return jmax (a, jmax (b, c, d)); }
  855. /** Returns the smaller of two values. */
  856. template <typename Type>
  857. inline Type jmin (const Type a, const Type b) { return (b < a) ? b : a; }
  858. /** Returns the smaller of three values. */
  859. template <typename Type>
  860. inline Type jmin (const Type a, const Type b, const Type c) { return (b < a) ? ((c < b) ? c : b) : ((c < a) ? c : a); }
  861. /** Returns the smaller of four values. */
  862. template <typename Type>
  863. inline Type jmin (const Type a, const Type b, const Type c, const Type d) { return jmin (a, jmin (b, c, d)); }
  864. /** Scans an array of values, returning the minimum value that it contains. */
  865. template <typename Type>
  866. const Type findMinimum (const Type* data, int numValues)
  867. {
  868. if (numValues <= 0)
  869. return Type();
  870. Type result (*data++);
  871. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  872. {
  873. const Type& v = *data++;
  874. if (v < result) result = v;
  875. }
  876. return result;
  877. }
  878. /** Scans an array of values, returning the minimum value that it contains. */
  879. template <typename Type>
  880. const Type findMaximum (const Type* values, int numValues)
  881. {
  882. if (numValues <= 0)
  883. return Type();
  884. Type result (*values++);
  885. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  886. {
  887. const Type& v = *values++;
  888. if (result > v) result = v;
  889. }
  890. return result;
  891. }
  892. /** Scans an array of values, returning the minimum and maximum values that it contains. */
  893. template <typename Type>
  894. void findMinAndMax (const Type* values, int numValues, Type& lowest, Type& highest)
  895. {
  896. if (numValues <= 0)
  897. {
  898. lowest = Type();
  899. highest = Type();
  900. }
  901. else
  902. {
  903. Type mn (*values++);
  904. Type mx (mn);
  905. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  906. {
  907. const Type& v = *values++;
  908. if (mx < v) mx = v;
  909. if (v < mn) mn = v;
  910. }
  911. lowest = mn;
  912. highest = mx;
  913. }
  914. }
  915. /** Constrains a value to keep it within a given range.
  916. This will check that the specified value lies between the lower and upper bounds
  917. specified, and if not, will return the nearest value that would be in-range. Effectively,
  918. it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
  919. Note that it expects that lowerLimit <= upperLimit. If this isn't true,
  920. the results will be unpredictable.
  921. @param lowerLimit the minimum value to return
  922. @param upperLimit the maximum value to return
  923. @param valueToConstrain the value to try to return
  924. @returns the closest value to valueToConstrain which lies between lowerLimit
  925. and upperLimit (inclusive)
  926. @see jlimit0To, jmin, jmax
  927. */
  928. template <typename Type>
  929. inline Type jlimit (const Type lowerLimit,
  930. const Type upperLimit,
  931. const Type valueToConstrain) noexcept
  932. {
  933. jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
  934. return (valueToConstrain < lowerLimit) ? lowerLimit
  935. : ((upperLimit < valueToConstrain) ? upperLimit
  936. : valueToConstrain);
  937. }
  938. /** Returns true if a value is at least zero, and also below a specified upper limit.
  939. This is basically a quicker way to write:
  940. @code valueToTest >= 0 && valueToTest < upperLimit
  941. @endcode
  942. */
  943. template <typename Type>
  944. inline bool isPositiveAndBelow (Type valueToTest, Type upperLimit) noexcept
  945. {
  946. jassert (Type() <= upperLimit); // makes no sense to call this if the upper limit is itself below zero..
  947. return Type() <= valueToTest && valueToTest < upperLimit;
  948. }
  949. #if ! JUCE_VC6
  950. template <>
  951. inline bool isPositiveAndBelow (const int valueToTest, const int upperLimit) noexcept
  952. {
  953. jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero..
  954. return static_cast <unsigned int> (valueToTest) < static_cast <unsigned int> (upperLimit);
  955. }
  956. #endif
  957. /** Returns true if a value is at least zero, and also less than or equal to a specified upper limit.
  958. This is basically a quicker way to write:
  959. @code valueToTest >= 0 && valueToTest <= upperLimit
  960. @endcode
  961. */
  962. template <typename Type>
  963. inline bool isPositiveAndNotGreaterThan (Type valueToTest, Type upperLimit) noexcept
  964. {
  965. jassert (Type() <= upperLimit); // makes no sense to call this if the upper limit is itself below zero..
  966. return Type() <= valueToTest && valueToTest <= upperLimit;
  967. }
  968. #if ! JUCE_VC6
  969. template <>
  970. inline bool isPositiveAndNotGreaterThan (const int valueToTest, const int upperLimit) noexcept
  971. {
  972. jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero..
  973. return static_cast <unsigned int> (valueToTest) <= static_cast <unsigned int> (upperLimit);
  974. }
  975. #endif
  976. /** Handy function to swap two values. */
  977. template <typename Type>
  978. inline void swapVariables (Type& variable1, Type& variable2)
  979. {
  980. std::swap (variable1, variable2);
  981. }
  982. #if JUCE_VC6
  983. #define numElementsInArray(X) (sizeof((X)) / sizeof(0[X]))
  984. #else
  985. /** Handy function for getting the number of elements in a simple const C array.
  986. E.g.
  987. @code
  988. static int myArray[] = { 1, 2, 3 };
  989. int numElements = numElementsInArray (myArray) // returns 3
  990. @endcode
  991. */
  992. template <typename Type, int N>
  993. inline int numElementsInArray (Type (&array)[N])
  994. {
  995. (void) array; // (required to avoid a spurious warning in MS compilers)
  996. (void) sizeof (0[array]); // This line should cause an error if you pass an object with a user-defined subscript operator
  997. return N;
  998. }
  999. #endif
  1000. // Some useful maths functions that aren't always present with all compilers and build settings.
  1001. /** Using juce_hypot is easier than dealing with the different types of hypot function
  1002. that are provided by the various platforms and compilers. */
  1003. template <typename Type>
  1004. inline Type juce_hypot (Type a, Type b) noexcept
  1005. {
  1006. #if JUCE_WINDOWS
  1007. return static_cast <Type> (_hypot (a, b));
  1008. #else
  1009. return static_cast <Type> (hypot (a, b));
  1010. #endif
  1011. }
  1012. /** 64-bit abs function. */
  1013. inline int64 abs64 (const int64 n) noexcept
  1014. {
  1015. return (n >= 0) ? n : -n;
  1016. }
  1017. /** This templated negate function will negate pointers as well as integers */
  1018. template <typename Type>
  1019. inline Type juce_negate (Type n) noexcept
  1020. {
  1021. return sizeof (Type) == 1 ? (Type) -(signed char) n
  1022. : (sizeof (Type) == 2 ? (Type) -(short) n
  1023. : (sizeof (Type) == 4 ? (Type) -(int) n
  1024. : ((Type) -(int64) n)));
  1025. }
  1026. /** This templated negate function will negate pointers as well as integers */
  1027. template <typename Type>
  1028. inline Type* juce_negate (Type* n) noexcept
  1029. {
  1030. return (Type*) -(pointer_sized_int) n;
  1031. }
  1032. /** A predefined value for Pi, at double-precision.
  1033. @see float_Pi
  1034. */
  1035. const double double_Pi = 3.1415926535897932384626433832795;
  1036. /** A predefined value for Pi, at sngle-precision.
  1037. @see double_Pi
  1038. */
  1039. const float float_Pi = 3.14159265358979323846f;
  1040. /** The isfinite() method seems to vary between platforms, so this is a
  1041. platform-independent function for it.
  1042. */
  1043. template <typename FloatingPointType>
  1044. inline bool juce_isfinite (FloatingPointType value)
  1045. {
  1046. #if JUCE_WINDOWS
  1047. return _finite (value);
  1048. #elif JUCE_ANDROID
  1049. return isfinite (value);
  1050. #else
  1051. return std::isfinite (value);
  1052. #endif
  1053. }
  1054. /** Fast floating-point-to-integer conversion.
  1055. This is faster than using the normal c++ cast to convert a float to an int, and
  1056. it will round the value to the nearest integer, rather than rounding it down
  1057. like the normal cast does.
  1058. Note that this routine gets its speed at the expense of some accuracy, and when
  1059. rounding values whose floating point component is exactly 0.5, odd numbers and
  1060. even numbers will be rounded up or down differently.
  1061. */
  1062. template <typename FloatType>
  1063. inline int roundToInt (const FloatType value) noexcept
  1064. {
  1065. union { int asInt[2]; double asDouble; } n;
  1066. n.asDouble = ((double) value) + 6755399441055744.0;
  1067. #if JUCE_BIG_ENDIAN
  1068. return n.asInt [1];
  1069. #else
  1070. return n.asInt [0];
  1071. #endif
  1072. }
  1073. /** Fast floating-point-to-integer conversion.
  1074. This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
  1075. fine for values above zero, but negative numbers are rounded the wrong way.
  1076. */
  1077. inline int roundToIntAccurate (const double value) noexcept
  1078. {
  1079. return roundToInt (value + 1.5e-8);
  1080. }
  1081. /** Fast floating-point-to-integer conversion.
  1082. This is faster than using the normal c++ cast to convert a double to an int, and
  1083. it will round the value to the nearest integer, rather than rounding it down
  1084. like the normal cast does.
  1085. Note that this routine gets its speed at the expense of some accuracy, and when
  1086. rounding values whose floating point component is exactly 0.5, odd numbers and
  1087. even numbers will be rounded up or down differently. For a more accurate conversion,
  1088. see roundDoubleToIntAccurate().
  1089. */
  1090. inline int roundDoubleToInt (const double value) noexcept
  1091. {
  1092. return roundToInt (value);
  1093. }
  1094. /** Fast floating-point-to-integer conversion.
  1095. This is faster than using the normal c++ cast to convert a float to an int, and
  1096. it will round the value to the nearest integer, rather than rounding it down
  1097. like the normal cast does.
  1098. Note that this routine gets its speed at the expense of some accuracy, and when
  1099. rounding values whose floating point component is exactly 0.5, odd numbers and
  1100. even numbers will be rounded up or down differently.
  1101. */
  1102. inline int roundFloatToInt (const float value) noexcept
  1103. {
  1104. return roundToInt (value);
  1105. }
  1106. #if (JUCE_INTEL && JUCE_32BIT) || defined (DOXYGEN)
  1107. /** This macro can be applied to a float variable to check whether it contains a denormalised
  1108. value, and to normalise it if necessary.
  1109. On CPUs that aren't vulnerable to denormalisation problems, this will have no effect.
  1110. */
  1111. #define JUCE_UNDENORMALISE(x) x += 1.0f; x -= 1.0f;
  1112. #else
  1113. #define JUCE_UNDENORMALISE(x)
  1114. #endif
  1115. /** This namespace contains a few template classes for helping work out class type variations.
  1116. */
  1117. namespace TypeHelpers
  1118. {
  1119. #if JUCE_VC8_OR_EARLIER
  1120. #define PARAMETER_TYPE(type) const type&
  1121. #else
  1122. /** The ParameterType struct is used to find the best type to use when passing some kind
  1123. of object as a parameter.
  1124. Of course, this is only likely to be useful in certain esoteric template situations.
  1125. Because "typename TypeHelpers::ParameterType<SomeClass>::type" is a bit of a mouthful, there's
  1126. a PARAMETER_TYPE(SomeClass) macro that you can use to get the same effect.
  1127. E.g. "myFunction (PARAMETER_TYPE (int), PARAMETER_TYPE (MyObject))"
  1128. would evaluate to "myfunction (int, const MyObject&)", keeping any primitive types as
  1129. pass-by-value, but passing objects as a const reference, to avoid copying.
  1130. */
  1131. template <typename Type> struct ParameterType { typedef const Type& type; };
  1132. #if ! DOXYGEN
  1133. template <typename Type> struct ParameterType <Type&> { typedef Type& type; };
  1134. template <typename Type> struct ParameterType <Type*> { typedef Type* type; };
  1135. template <> struct ParameterType <char> { typedef char type; };
  1136. template <> struct ParameterType <unsigned char> { typedef unsigned char type; };
  1137. template <> struct ParameterType <short> { typedef short type; };
  1138. template <> struct ParameterType <unsigned short> { typedef unsigned short type; };
  1139. template <> struct ParameterType <int> { typedef int type; };
  1140. template <> struct ParameterType <unsigned int> { typedef unsigned int type; };
  1141. template <> struct ParameterType <long> { typedef long type; };
  1142. template <> struct ParameterType <unsigned long> { typedef unsigned long type; };
  1143. template <> struct ParameterType <int64> { typedef int64 type; };
  1144. template <> struct ParameterType <uint64> { typedef uint64 type; };
  1145. template <> struct ParameterType <bool> { typedef bool type; };
  1146. template <> struct ParameterType <float> { typedef float type; };
  1147. template <> struct ParameterType <double> { typedef double type; };
  1148. #endif
  1149. /** A helpful macro to simplify the use of the ParameterType template.
  1150. @see ParameterType
  1151. */
  1152. #define PARAMETER_TYPE(a) typename TypeHelpers::ParameterType<a>::type
  1153. #endif
  1154. }
  1155. #endif // __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  1156. /*** End of inlined file: juce_MathsFunctions.h ***/
  1157. /*** Start of inlined file: juce_ByteOrder.h ***/
  1158. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  1159. #define __JUCE_BYTEORDER_JUCEHEADER__
  1160. /** Contains static methods for converting the byte order between different
  1161. endiannesses.
  1162. */
  1163. class JUCE_API ByteOrder
  1164. {
  1165. public:
  1166. /** Swaps the upper and lower bytes of a 16-bit integer. */
  1167. static uint16 swap (uint16 value);
  1168. /** Reverses the order of the 4 bytes in a 32-bit integer. */
  1169. static uint32 swap (uint32 value);
  1170. /** Reverses the order of the 8 bytes in a 64-bit integer. */
  1171. static uint64 swap (uint64 value);
  1172. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  1173. static uint16 swapIfBigEndian (uint16 value);
  1174. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  1175. static uint32 swapIfBigEndian (uint32 value);
  1176. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  1177. static uint64 swapIfBigEndian (uint64 value);
  1178. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  1179. static uint16 swapIfLittleEndian (uint16 value);
  1180. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  1181. static uint32 swapIfLittleEndian (uint32 value);
  1182. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  1183. static uint64 swapIfLittleEndian (uint64 value);
  1184. /** Turns 4 bytes into a little-endian integer. */
  1185. static uint32 littleEndianInt (const void* bytes);
  1186. /** Turns 2 bytes into a little-endian integer. */
  1187. static uint16 littleEndianShort (const void* bytes);
  1188. /** Turns 4 bytes into a big-endian integer. */
  1189. static uint32 bigEndianInt (const void* bytes);
  1190. /** Turns 2 bytes into a big-endian integer. */
  1191. static uint16 bigEndianShort (const void* bytes);
  1192. /** Converts 3 little-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1193. static int littleEndian24Bit (const char* bytes);
  1194. /** Converts 3 big-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1195. static int bigEndian24Bit (const char* bytes);
  1196. /** Copies a 24-bit number to 3 little-endian bytes. */
  1197. static void littleEndian24BitToChars (int value, char* destBytes);
  1198. /** Copies a 24-bit number to 3 big-endian bytes. */
  1199. static void bigEndian24BitToChars (int value, char* destBytes);
  1200. /** Returns true if the current CPU is big-endian. */
  1201. static bool isBigEndian();
  1202. private:
  1203. ByteOrder();
  1204. JUCE_DECLARE_NON_COPYABLE (ByteOrder);
  1205. };
  1206. #if JUCE_USE_INTRINSICS && ! defined (__INTEL_COMPILER)
  1207. #pragma intrinsic (_byteswap_ulong)
  1208. #endif
  1209. inline uint16 ByteOrder::swap (uint16 n)
  1210. {
  1211. #if JUCE_USE_INTRINSICSxxx // agh - the MS compiler has an internal error when you try to use this intrinsic!
  1212. return static_cast <uint16> (_byteswap_ushort (n));
  1213. #else
  1214. return static_cast <uint16> ((n << 8) | (n >> 8));
  1215. #endif
  1216. }
  1217. inline uint32 ByteOrder::swap (uint32 n)
  1218. {
  1219. #if JUCE_MAC || JUCE_IOS
  1220. return OSSwapInt32 (n);
  1221. #elif JUCE_GCC && JUCE_INTEL
  1222. asm("bswap %%eax" : "=a"(n) : "a"(n));
  1223. return n;
  1224. #elif JUCE_USE_INTRINSICS
  1225. return _byteswap_ulong (n);
  1226. #elif JUCE_MSVC
  1227. __asm {
  1228. mov eax, n
  1229. bswap eax
  1230. mov n, eax
  1231. }
  1232. return n;
  1233. #elif JUCE_ANDROID
  1234. return bswap_32 (n);
  1235. #else
  1236. return (n << 24) | (n >> 24) | ((n & 0xff00) << 8) | ((n & 0xff0000) >> 8);
  1237. #endif
  1238. }
  1239. inline uint64 ByteOrder::swap (uint64 value)
  1240. {
  1241. #if JUCE_MAC || JUCE_IOS
  1242. return OSSwapInt64 (value);
  1243. #elif JUCE_USE_INTRINSICS
  1244. return _byteswap_uint64 (value);
  1245. #else
  1246. return (((int64) swap ((uint32) value)) << 32) | swap ((uint32) (value >> 32));
  1247. #endif
  1248. }
  1249. #if JUCE_LITTLE_ENDIAN
  1250. inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return v; }
  1251. inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return v; }
  1252. inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return v; }
  1253. inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return swap (v); }
  1254. inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return swap (v); }
  1255. inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return swap (v); }
  1256. inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return *static_cast <const uint32*> (bytes); }
  1257. inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return *static_cast <const uint16*> (bytes); }
  1258. inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return swap (*static_cast <const uint32*> (bytes)); }
  1259. inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return swap (*static_cast <const uint16*> (bytes)); }
  1260. inline bool ByteOrder::isBigEndian() { return false; }
  1261. #else
  1262. inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return swap (v); }
  1263. inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return swap (v); }
  1264. inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return swap (v); }
  1265. inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return v; }
  1266. inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return v; }
  1267. inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return v; }
  1268. inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return swap (*static_cast <const uint32*> (bytes)); }
  1269. inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return swap (*static_cast <const uint16*> (bytes)); }
  1270. inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return *static_cast <const uint32*> (bytes); }
  1271. inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return *static_cast <const uint16*> (bytes); }
  1272. inline bool ByteOrder::isBigEndian() { return true; }
  1273. #endif
  1274. inline int ByteOrder::littleEndian24Bit (const char* const bytes) { return (((int) bytes[2]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[0]); }
  1275. inline int ByteOrder::bigEndian24Bit (const char* const bytes) { return (((int) bytes[0]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[2]); }
  1276. 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); }
  1277. 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); }
  1278. #endif // __JUCE_BYTEORDER_JUCEHEADER__
  1279. /*** End of inlined file: juce_ByteOrder.h ***/
  1280. /*** Start of inlined file: juce_Logger.h ***/
  1281. #ifndef __JUCE_LOGGER_JUCEHEADER__
  1282. #define __JUCE_LOGGER_JUCEHEADER__
  1283. /*** Start of inlined file: juce_String.h ***/
  1284. #ifndef __JUCE_STRING_JUCEHEADER__
  1285. #define __JUCE_STRING_JUCEHEADER__
  1286. /*** Start of inlined file: juce_CharacterFunctions.h ***/
  1287. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1288. #define __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1289. #if JUCE_WINDOWS && ! DOXYGEN
  1290. #define JUCE_NATIVE_WCHAR_IS_UTF8 0
  1291. #define JUCE_NATIVE_WCHAR_IS_UTF16 1
  1292. #define JUCE_NATIVE_WCHAR_IS_UTF32 0
  1293. #else
  1294. /** This macro will be set to 1 if the compiler's native wchar_t is an 8-bit type. */
  1295. #define JUCE_NATIVE_WCHAR_IS_UTF8 0
  1296. /** This macro will be set to 1 if the compiler's native wchar_t is a 16-bit type. */
  1297. #define JUCE_NATIVE_WCHAR_IS_UTF16 0
  1298. /** This macro will be set to 1 if the compiler's native wchar_t is a 32-bit type. */
  1299. #define JUCE_NATIVE_WCHAR_IS_UTF32 1
  1300. #endif
  1301. #if JUCE_NATIVE_WCHAR_IS_UTF32 || DOXYGEN
  1302. /** A platform-independent 32-bit unicode character type. */
  1303. typedef wchar_t juce_wchar;
  1304. #else
  1305. typedef uint32 juce_wchar;
  1306. #endif
  1307. /** This macro is deprecated, but preserved for compatibility with old code.*/
  1308. #define JUCE_T(stringLiteral) (L##stringLiteral)
  1309. #if ! JUCE_DONT_DEFINE_MACROS
  1310. /** The 'T' macro is an alternative for using the "L" prefix in front of a string literal.
  1311. This macro is deprectated, but kept here for compatibility with old code. The best (i.e.
  1312. most portable) way to encode your string literals is just as standard 8-bit strings, but
  1313. using escaped utf-8 character codes for extended characters.
  1314. Because the 'T' symbol is occasionally used inside 3rd-party library headers which you
  1315. may need to include after juce.h, you can use the juce_withoutMacros.h file (in
  1316. the juce/src directory) to avoid defining this macro. See the comments in
  1317. juce_withoutMacros.h for more info.
  1318. */
  1319. #define T(stringLiteral) JUCE_T(stringLiteral)
  1320. #endif
  1321. #undef max
  1322. #undef min
  1323. /**
  1324. A set of methods for manipulating characters and character strings.
  1325. These are defined as wrappers around the basic C string handlers, to provide
  1326. a clean, cross-platform layer, (because various platforms differ in the
  1327. range of C library calls that they provide).
  1328. @see String
  1329. */
  1330. class JUCE_API CharacterFunctions
  1331. {
  1332. public:
  1333. static juce_wchar toUpperCase (juce_wchar character) noexcept;
  1334. static juce_wchar toLowerCase (juce_wchar character) noexcept;
  1335. static bool isUpperCase (juce_wchar character) noexcept;
  1336. static bool isLowerCase (juce_wchar character) noexcept;
  1337. static bool isWhitespace (char character) noexcept;
  1338. static bool isWhitespace (juce_wchar character) noexcept;
  1339. static bool isDigit (char character) noexcept;
  1340. static bool isDigit (juce_wchar character) noexcept;
  1341. static bool isLetter (char character) noexcept;
  1342. static bool isLetter (juce_wchar character) noexcept;
  1343. static bool isLetterOrDigit (char character) noexcept;
  1344. static bool isLetterOrDigit (juce_wchar character) noexcept;
  1345. /** Returns 0 to 16 for '0' to 'F", or -1 for characters that aren't a legal hex digit. */
  1346. static int getHexDigitValue (juce_wchar digit) noexcept;
  1347. template <typename CharPointerType>
  1348. static double readDoubleValue (CharPointerType& text) noexcept
  1349. {
  1350. double result[3] = { 0 }, accumulator[2] = { 0 };
  1351. int exponentAdjustment[2] = { 0 }, exponentAccumulator[2] = { -1, -1 };
  1352. int exponent = 0, decPointIndex = 0, digit = 0;
  1353. int lastDigit = 0, numSignificantDigits = 0;
  1354. bool isNegative = false, digitsFound = false;
  1355. const int maxSignificantDigits = 15 + 2;
  1356. text = text.findEndOfWhitespace();
  1357. juce_wchar c = *text;
  1358. switch (c)
  1359. {
  1360. case '-': isNegative = true; // fall-through..
  1361. case '+': c = *++text;
  1362. }
  1363. switch (c)
  1364. {
  1365. case 'n':
  1366. case 'N':
  1367. if ((text[1] == 'a' || text[1] == 'A') && (text[2] == 'n' || text[2] == 'N'))
  1368. return std::numeric_limits<double>::quiet_NaN();
  1369. break;
  1370. case 'i':
  1371. case 'I':
  1372. if ((text[1] == 'n' || text[1] == 'N') && (text[2] == 'f' || text[2] == 'F'))
  1373. return std::numeric_limits<double>::infinity();
  1374. break;
  1375. }
  1376. for (;;)
  1377. {
  1378. if (text.isDigit())
  1379. {
  1380. lastDigit = digit;
  1381. digit = text.getAndAdvance() - '0';
  1382. digitsFound = true;
  1383. if (decPointIndex != 0)
  1384. exponentAdjustment[1]++;
  1385. if (numSignificantDigits == 0 && digit == 0)
  1386. continue;
  1387. if (++numSignificantDigits > maxSignificantDigits)
  1388. {
  1389. if (digit > 5)
  1390. ++accumulator [decPointIndex];
  1391. else if (digit == 5 && (lastDigit & 1) != 0)
  1392. ++accumulator [decPointIndex];
  1393. if (decPointIndex > 0)
  1394. exponentAdjustment[1]--;
  1395. else
  1396. exponentAdjustment[0]++;
  1397. while (text.isDigit())
  1398. {
  1399. ++text;
  1400. if (decPointIndex == 0)
  1401. exponentAdjustment[0]++;
  1402. }
  1403. }
  1404. else
  1405. {
  1406. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  1407. if (accumulator [decPointIndex] > maxAccumulatorValue)
  1408. {
  1409. result [decPointIndex] = mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  1410. + accumulator [decPointIndex];
  1411. accumulator [decPointIndex] = 0;
  1412. exponentAccumulator [decPointIndex] = 0;
  1413. }
  1414. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  1415. exponentAccumulator [decPointIndex]++;
  1416. }
  1417. }
  1418. else if (decPointIndex == 0 && *text == '.')
  1419. {
  1420. ++text;
  1421. decPointIndex = 1;
  1422. if (numSignificantDigits > maxSignificantDigits)
  1423. {
  1424. while (text.isDigit())
  1425. ++text;
  1426. break;
  1427. }
  1428. }
  1429. else
  1430. {
  1431. break;
  1432. }
  1433. }
  1434. result[0] = mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  1435. if (decPointIndex != 0)
  1436. result[1] = mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  1437. c = *text;
  1438. if ((c == 'e' || c == 'E') && digitsFound)
  1439. {
  1440. bool negativeExponent = false;
  1441. switch (*++text)
  1442. {
  1443. case '-': negativeExponent = true; // fall-through..
  1444. case '+': ++text;
  1445. }
  1446. while (text.isDigit())
  1447. exponent = (exponent * 10) + (text.getAndAdvance() - '0');
  1448. if (negativeExponent)
  1449. exponent = -exponent;
  1450. }
  1451. double r = mulexp10 (result[0], exponent + exponentAdjustment[0]);
  1452. if (decPointIndex != 0)
  1453. r += mulexp10 (result[1], exponent - exponentAdjustment[1]);
  1454. return isNegative ? -r : r;
  1455. }
  1456. template <typename CharPointerType>
  1457. static double getDoubleValue (const CharPointerType& text) noexcept
  1458. {
  1459. CharPointerType t (text);
  1460. return readDoubleValue (t);
  1461. }
  1462. template <typename IntType, typename CharPointerType>
  1463. static IntType getIntValue (const CharPointerType& text) noexcept
  1464. {
  1465. IntType v = 0;
  1466. CharPointerType s (text.findEndOfWhitespace());
  1467. const bool isNeg = *s == '-';
  1468. if (isNeg)
  1469. ++s;
  1470. for (;;)
  1471. {
  1472. const juce_wchar c = s.getAndAdvance();
  1473. if (c >= '0' && c <= '9')
  1474. v = v * 10 + (IntType) (c - '0');
  1475. else
  1476. break;
  1477. }
  1478. return isNeg ? -v : v;
  1479. }
  1480. template <typename CharPointerType>
  1481. static size_t lengthUpTo (CharPointerType text, const size_t maxCharsToCount) noexcept
  1482. {
  1483. size_t len = 0;
  1484. while (len < maxCharsToCount && text.getAndAdvance() != 0)
  1485. ++len;
  1486. return len;
  1487. }
  1488. template <typename CharPointerType>
  1489. static size_t lengthUpTo (CharPointerType start, const CharPointerType& end) noexcept
  1490. {
  1491. size_t len = 0;
  1492. while (start < end && start.getAndAdvance() != 0)
  1493. ++len;
  1494. return len;
  1495. }
  1496. template <typename DestCharPointerType, typename SrcCharPointerType>
  1497. static void copyAll (DestCharPointerType& dest, SrcCharPointerType src) noexcept
  1498. {
  1499. for (;;)
  1500. {
  1501. const juce_wchar c = src.getAndAdvance();
  1502. if (c == 0)
  1503. break;
  1504. dest.write (c);
  1505. }
  1506. dest.writeNull();
  1507. }
  1508. template <typename DestCharPointerType, typename SrcCharPointerType>
  1509. static int copyWithDestByteLimit (DestCharPointerType& dest, SrcCharPointerType src, int maxBytes) noexcept
  1510. {
  1511. typename DestCharPointerType::CharType const* const startAddress = dest.getAddress();
  1512. maxBytes -= sizeof (typename DestCharPointerType::CharType); // (allow for a terminating null)
  1513. for (;;)
  1514. {
  1515. const juce_wchar c = src.getAndAdvance();
  1516. const int bytesNeeded = (int) DestCharPointerType::getBytesRequiredFor (c);
  1517. maxBytes -= bytesNeeded;
  1518. if (c == 0 || maxBytes < 0)
  1519. break;
  1520. dest.write (c);
  1521. }
  1522. dest.writeNull();
  1523. return getAddressDifference (dest.getAddress(), startAddress);
  1524. }
  1525. template <typename DestCharPointerType, typename SrcCharPointerType>
  1526. static void copyWithCharLimit (DestCharPointerType& dest, SrcCharPointerType src, int maxChars) noexcept
  1527. {
  1528. while (--maxChars > 0)
  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 CharPointerType1, typename CharPointerType2>
  1538. static int compare (CharPointerType1 s1, CharPointerType2 s2) noexcept
  1539. {
  1540. for (;;)
  1541. {
  1542. const int c1 = (int) s1.getAndAdvance();
  1543. const int c2 = (int) s2.getAndAdvance();
  1544. const int diff = c1 - c2;
  1545. if (diff != 0)
  1546. return diff < 0 ? -1 : 1;
  1547. else if (c1 == 0)
  1548. break;
  1549. }
  1550. return 0;
  1551. }
  1552. template <typename CharPointerType1, typename CharPointerType2>
  1553. static int compareUpTo (CharPointerType1 s1, CharPointerType2 s2, int maxChars) noexcept
  1554. {
  1555. while (--maxChars >= 0)
  1556. {
  1557. const int c1 = (int) s1.getAndAdvance();
  1558. const int c2 = (int) s2.getAndAdvance();
  1559. const int diff = c1 - c2;
  1560. if (diff != 0)
  1561. return diff < 0 ? -1 : 1;
  1562. else if (c1 == 0)
  1563. break;
  1564. }
  1565. return 0;
  1566. }
  1567. template <typename CharPointerType1, typename CharPointerType2>
  1568. static int compareIgnoreCase (CharPointerType1 s1, CharPointerType2 s2) noexcept
  1569. {
  1570. for (;;)
  1571. {
  1572. int c1 = s1.toUpperCase();
  1573. int c2 = s2.toUpperCase();
  1574. ++s1;
  1575. ++s2;
  1576. const int diff = c1 - c2;
  1577. if (diff != 0)
  1578. return diff < 0 ? -1 : 1;
  1579. else if (c1 == 0)
  1580. break;
  1581. }
  1582. return 0;
  1583. }
  1584. template <typename CharPointerType1, typename CharPointerType2>
  1585. static int compareIgnoreCaseUpTo (CharPointerType1 s1, CharPointerType2 s2, int maxChars) noexcept
  1586. {
  1587. while (--maxChars >= 0)
  1588. {
  1589. int c1 = s1.toUpperCase();
  1590. int c2 = s2.toUpperCase();
  1591. ++s1;
  1592. ++s2;
  1593. const int diff = c1 - c2;
  1594. if (diff != 0)
  1595. return diff < 0 ? -1 : 1;
  1596. else if (c1 == 0)
  1597. break;
  1598. }
  1599. return 0;
  1600. }
  1601. template <typename CharPointerType1, typename CharPointerType2>
  1602. static int indexOf (CharPointerType1 haystack, const CharPointerType2& needle) noexcept
  1603. {
  1604. int index = 0;
  1605. const int needleLength = (int) needle.length();
  1606. for (;;)
  1607. {
  1608. if (haystack.compareUpTo (needle, needleLength) == 0)
  1609. return index;
  1610. if (haystack.getAndAdvance() == 0)
  1611. return -1;
  1612. ++index;
  1613. }
  1614. }
  1615. template <typename CharPointerType1, typename CharPointerType2>
  1616. static int indexOfIgnoreCase (CharPointerType1 haystack, const CharPointerType2& needle) noexcept
  1617. {
  1618. int index = 0;
  1619. const int needleLength = (int) needle.length();
  1620. for (;;)
  1621. {
  1622. if (haystack.compareIgnoreCaseUpTo (needle, needleLength) == 0)
  1623. return index;
  1624. if (haystack.getAndAdvance() == 0)
  1625. return -1;
  1626. ++index;
  1627. }
  1628. }
  1629. template <typename Type>
  1630. static int indexOfChar (Type text, const juce_wchar charToFind) noexcept
  1631. {
  1632. int i = 0;
  1633. while (! text.isEmpty())
  1634. {
  1635. if (text.getAndAdvance() == charToFind)
  1636. return i;
  1637. ++i;
  1638. }
  1639. return -1;
  1640. }
  1641. template <typename Type>
  1642. static int indexOfCharIgnoreCase (Type text, juce_wchar charToFind) noexcept
  1643. {
  1644. charToFind = CharacterFunctions::toLowerCase (charToFind);
  1645. int i = 0;
  1646. while (! text.isEmpty())
  1647. {
  1648. if (text.toLowerCase() == charToFind)
  1649. return i;
  1650. ++text;
  1651. ++i;
  1652. }
  1653. return -1;
  1654. }
  1655. template <typename Type>
  1656. static Type findEndOfWhitespace (const Type& text) noexcept
  1657. {
  1658. Type p (text);
  1659. while (p.isWhitespace())
  1660. ++p;
  1661. return p;
  1662. }
  1663. template <typename Type>
  1664. static Type findEndOfToken (const Type& text, const Type& breakCharacters, const Type& quoteCharacters)
  1665. {
  1666. Type t (text);
  1667. juce_wchar currentQuoteChar = 0;
  1668. while (! t.isEmpty())
  1669. {
  1670. const juce_wchar c = t.getAndAdvance();
  1671. if (currentQuoteChar == 0 && breakCharacters.indexOf (c) >= 0)
  1672. {
  1673. --t;
  1674. break;
  1675. }
  1676. if (quoteCharacters.indexOf (c) >= 0)
  1677. {
  1678. if (currentQuoteChar == 0)
  1679. currentQuoteChar = c;
  1680. else if (currentQuoteChar == c)
  1681. currentQuoteChar = 0;
  1682. }
  1683. }
  1684. return t;
  1685. }
  1686. private:
  1687. static double mulexp10 (const double value, int exponent) noexcept;
  1688. };
  1689. #endif // __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1690. /*** End of inlined file: juce_CharacterFunctions.h ***/
  1691. #ifndef JUCE_STRING_UTF_TYPE
  1692. #define JUCE_STRING_UTF_TYPE 8
  1693. #endif
  1694. #if JUCE_MSVC
  1695. #pragma warning (push)
  1696. #pragma warning (disable: 4514 4996)
  1697. #endif
  1698. /*** Start of inlined file: juce_Atomic.h ***/
  1699. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  1700. #define __JUCE_ATOMIC_JUCEHEADER__
  1701. /**
  1702. Simple class to hold a primitive value and perform atomic operations on it.
  1703. The type used must be a 32 or 64 bit primitive, like an int, pointer, etc.
  1704. There are methods to perform most of the basic atomic operations.
  1705. */
  1706. template <typename Type>
  1707. class Atomic
  1708. {
  1709. public:
  1710. /** Creates a new value, initialised to zero. */
  1711. inline Atomic() noexcept
  1712. : value (0)
  1713. {
  1714. }
  1715. /** Creates a new value, with a given initial value. */
  1716. inline Atomic (const Type initialValue) noexcept
  1717. : value (initialValue)
  1718. {
  1719. }
  1720. /** Copies another value (atomically). */
  1721. inline Atomic (const Atomic& other) noexcept
  1722. : value (other.get())
  1723. {
  1724. }
  1725. /** Destructor. */
  1726. inline ~Atomic() noexcept
  1727. {
  1728. // This class can only be used for types which are 32 or 64 bits in size.
  1729. static_jassert (sizeof (Type) == 4 || sizeof (Type) == 8);
  1730. }
  1731. /** Atomically reads and returns the current value. */
  1732. Type get() const noexcept;
  1733. /** Copies another value onto this one (atomically). */
  1734. inline Atomic& operator= (const Atomic& other) noexcept { exchange (other.get()); return *this; }
  1735. /** Copies another value onto this one (atomically). */
  1736. inline Atomic& operator= (const Type newValue) noexcept { exchange (newValue); return *this; }
  1737. /** Atomically sets the current value. */
  1738. void set (Type newValue) noexcept { exchange (newValue); }
  1739. /** Atomically sets the current value, returning the value that was replaced. */
  1740. Type exchange (Type value) noexcept;
  1741. /** Atomically adds a number to this value, returning the new value. */
  1742. Type operator+= (Type amountToAdd) noexcept;
  1743. /** Atomically subtracts a number from this value, returning the new value. */
  1744. Type operator-= (Type amountToSubtract) noexcept;
  1745. /** Atomically increments this value, returning the new value. */
  1746. Type operator++() noexcept;
  1747. /** Atomically decrements this value, returning the new value. */
  1748. Type operator--() noexcept;
  1749. /** Atomically compares this value with a target value, and if it is equal, sets
  1750. this to be equal to a new value.
  1751. This operation is the atomic equivalent of doing this:
  1752. @code
  1753. bool compareAndSetBool (Type newValue, Type valueToCompare)
  1754. {
  1755. if (get() == valueToCompare)
  1756. {
  1757. set (newValue);
  1758. return true;
  1759. }
  1760. return false;
  1761. }
  1762. @endcode
  1763. @returns true if the comparison was true and the value was replaced; false if
  1764. the comparison failed and the value was left unchanged.
  1765. @see compareAndSetValue
  1766. */
  1767. bool compareAndSetBool (Type newValue, Type valueToCompare) noexcept;
  1768. /** Atomically compares this value with a target value, and if it is equal, sets
  1769. this to be equal to a new value.
  1770. This operation is the atomic equivalent of doing this:
  1771. @code
  1772. Type compareAndSetValue (Type newValue, Type valueToCompare)
  1773. {
  1774. Type oldValue = get();
  1775. if (oldValue == valueToCompare)
  1776. set (newValue);
  1777. return oldValue;
  1778. }
  1779. @endcode
  1780. @returns the old value before it was changed.
  1781. @see compareAndSetBool
  1782. */
  1783. Type compareAndSetValue (Type newValue, Type valueToCompare) noexcept;
  1784. /** Implements a memory read/write barrier. */
  1785. static void memoryBarrier() noexcept;
  1786. #if JUCE_64BIT
  1787. JUCE_ALIGN (8)
  1788. #else
  1789. JUCE_ALIGN (4)
  1790. #endif
  1791. /** The raw value that this class operates on.
  1792. This is exposed publically in case you need to manipulate it directly
  1793. for performance reasons.
  1794. */
  1795. volatile Type value;
  1796. private:
  1797. static inline Type castFrom32Bit (int32 value) noexcept { return *(Type*) &value; }
  1798. static inline Type castFrom64Bit (int64 value) noexcept { return *(Type*) &value; }
  1799. static inline int32 castTo32Bit (Type value) noexcept { return *(int32*) &value; }
  1800. static inline int64 castTo64Bit (Type value) noexcept { return *(int64*) &value; }
  1801. Type operator++ (int); // better to just use pre-increment with atomics..
  1802. Type operator-- (int);
  1803. };
  1804. /*
  1805. The following code is in the header so that the atomics can be inlined where possible...
  1806. */
  1807. #if (JUCE_IOS && (__IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_3_2 || ! defined (__IPHONE_3_2))) \
  1808. || (JUCE_MAC && (JUCE_PPC || __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2)))
  1809. #define JUCE_ATOMICS_MAC 1 // Older OSX builds using gcc4.1 or earlier
  1810. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  1811. #define JUCE_MAC_ATOMICS_VOLATILE
  1812. #else
  1813. #define JUCE_MAC_ATOMICS_VOLATILE volatile
  1814. #endif
  1815. #if JUCE_PPC || JUCE_IOS
  1816. // None of these atomics are available for PPC or for iPhoneOS 3.1 or earlier!!
  1817. template <typename Type> static Type OSAtomicAdd64Barrier (Type b, JUCE_MAC_ATOMICS_VOLATILE Type* a) noexcept { jassertfalse; return *a += b; }
  1818. template <typename Type> static Type OSAtomicIncrement64Barrier (JUCE_MAC_ATOMICS_VOLATILE Type* a) noexcept { jassertfalse; return ++*a; }
  1819. template <typename Type> static Type OSAtomicDecrement64Barrier (JUCE_MAC_ATOMICS_VOLATILE Type* a) noexcept { jassertfalse; return --*a; }
  1820. template <typename Type> static bool OSAtomicCompareAndSwap64Barrier (Type old, Type newValue, JUCE_MAC_ATOMICS_VOLATILE Type* value) noexcept
  1821. { jassertfalse; if (old == *value) { *value = newValue; return true; } return false; }
  1822. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  1823. #endif
  1824. #elif JUCE_ANDROID
  1825. #define JUCE_ATOMICS_ANDROID 1 // Android atomic functions
  1826. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  1827. #elif JUCE_GCC
  1828. #define JUCE_ATOMICS_GCC 1 // GCC with intrinsics
  1829. #if JUCE_IOS
  1830. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1 // (on the iphone, the 64-bit ops will compile but not link)
  1831. #endif
  1832. #else
  1833. #define JUCE_ATOMICS_WINDOWS 1 // Windows with intrinsics
  1834. #if JUCE_USE_INTRINSICS || JUCE_64BIT
  1835. #ifndef __INTEL_COMPILER
  1836. #pragma intrinsic (_InterlockedExchange, _InterlockedIncrement, _InterlockedDecrement, _InterlockedCompareExchange, \
  1837. _InterlockedCompareExchange64, _InterlockedExchangeAdd, _ReadWriteBarrier)
  1838. #endif
  1839. #define juce_InterlockedExchange(a, b) _InterlockedExchange(a, b)
  1840. #define juce_InterlockedIncrement(a) _InterlockedIncrement(a)
  1841. #define juce_InterlockedDecrement(a) _InterlockedDecrement(a)
  1842. #define juce_InterlockedExchangeAdd(a, b) _InterlockedExchangeAdd(a, b)
  1843. #define juce_InterlockedCompareExchange(a, b, c) _InterlockedCompareExchange(a, b, c)
  1844. #define juce_InterlockedCompareExchange64(a, b, c) _InterlockedCompareExchange64(a, b, c)
  1845. #define juce_MemoryBarrier _ReadWriteBarrier
  1846. #else
  1847. // (these are defined in juce_win32_Threads.cpp)
  1848. long juce_InterlockedExchange (volatile long* a, long b) noexcept;
  1849. long juce_InterlockedIncrement (volatile long* a) noexcept;
  1850. long juce_InterlockedDecrement (volatile long* a) noexcept;
  1851. long juce_InterlockedExchangeAdd (volatile long* a, long b) noexcept;
  1852. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) noexcept;
  1853. __int64 juce_InterlockedCompareExchange64 (volatile __int64* a, __int64 b, __int64 c) noexcept;
  1854. inline void juce_MemoryBarrier() noexcept { long x = 0; juce_InterlockedIncrement (&x); }
  1855. #endif
  1856. #if JUCE_64BIT
  1857. #ifndef __INTEL_COMPILER
  1858. #pragma intrinsic (_InterlockedExchangeAdd64, _InterlockedExchange64, _InterlockedIncrement64, _InterlockedDecrement64)
  1859. #endif
  1860. #define juce_InterlockedExchangeAdd64(a, b) _InterlockedExchangeAdd64(a, b)
  1861. #define juce_InterlockedExchange64(a, b) _InterlockedExchange64(a, b)
  1862. #define juce_InterlockedIncrement64(a) _InterlockedIncrement64(a)
  1863. #define juce_InterlockedDecrement64(a) _InterlockedDecrement64(a)
  1864. #else
  1865. // None of these atomics are available in a 32-bit Windows build!!
  1866. template <typename Type> static Type juce_InterlockedExchangeAdd64 (volatile Type* a, Type b) noexcept { jassertfalse; Type old = *a; *a += b; return old; }
  1867. template <typename Type> static Type juce_InterlockedExchange64 (volatile Type* a, Type b) noexcept { jassertfalse; Type old = *a; *a = b; return old; }
  1868. template <typename Type> static Type juce_InterlockedIncrement64 (volatile Type* a) noexcept { jassertfalse; return ++*a; }
  1869. template <typename Type> static Type juce_InterlockedDecrement64 (volatile Type* a) noexcept { jassertfalse; return --*a; }
  1870. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  1871. #endif
  1872. #endif
  1873. #if JUCE_MSVC
  1874. #pragma warning (push)
  1875. #pragma warning (disable: 4311) // (truncation warning)
  1876. #endif
  1877. template <typename Type>
  1878. inline Type Atomic<Type>::get() const noexcept
  1879. {
  1880. #if JUCE_ATOMICS_MAC
  1881. return sizeof (Type) == 4 ? castFrom32Bit ((int32) OSAtomicAdd32Barrier ((int32_t) 0, (JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value))
  1882. : castFrom64Bit ((int64) OSAtomicAdd64Barrier ((int64_t) 0, (JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value));
  1883. #elif JUCE_ATOMICS_WINDOWS
  1884. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedExchangeAdd ((volatile long*) &value, (long) 0))
  1885. : castFrom64Bit ((int64) juce_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) 0));
  1886. #elif JUCE_ATOMICS_ANDROID
  1887. return value;
  1888. #elif JUCE_ATOMICS_GCC
  1889. return sizeof (Type) == 4 ? castFrom32Bit ((int32) __sync_add_and_fetch ((volatile int32*) &value, 0))
  1890. : castFrom64Bit ((int64) __sync_add_and_fetch ((volatile int64*) &value, 0));
  1891. #endif
  1892. }
  1893. template <typename Type>
  1894. inline Type Atomic<Type>::exchange (const Type newValue) noexcept
  1895. {
  1896. #if JUCE_ATOMICS_ANDROID
  1897. return castFrom32Bit (__atomic_swap (castTo32Bit (newValue), (volatile int*) &value));
  1898. #elif JUCE_ATOMICS_MAC || JUCE_ATOMICS_GCC
  1899. Type currentVal = value;
  1900. while (! compareAndSetBool (newValue, currentVal)) { currentVal = value; }
  1901. return currentVal;
  1902. #elif JUCE_ATOMICS_WINDOWS
  1903. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedExchange ((volatile long*) &value, (long) castTo32Bit (newValue)))
  1904. : castFrom64Bit ((int64) juce_InterlockedExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue)));
  1905. #endif
  1906. }
  1907. template <typename Type>
  1908. inline Type Atomic<Type>::operator+= (const Type amountToAdd) noexcept
  1909. {
  1910. #if JUCE_ATOMICS_MAC
  1911. return sizeof (Type) == 4 ? (Type) OSAtomicAdd32Barrier ((int32_t) castTo32Bit (amountToAdd), (JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1912. : (Type) OSAtomicAdd64Barrier ((int64_t) amountToAdd, (JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1913. #elif JUCE_ATOMICS_WINDOWS
  1914. return sizeof (Type) == 4 ? (Type) (juce_InterlockedExchangeAdd ((volatile long*) &value, (long) amountToAdd) + (long) amountToAdd)
  1915. : (Type) (juce_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) amountToAdd) + (__int64) amountToAdd);
  1916. #elif JUCE_ATOMICS_ANDROID
  1917. for (;;)
  1918. {
  1919. const Type oldValue (value);
  1920. const Type newValue (castFrom32Bit (castTo32Bit (oldValue) + castTo32Bit (amountToAdd)));
  1921. if (compareAndSetBool (newValue, oldValue))
  1922. return newValue;
  1923. }
  1924. #elif JUCE_ATOMICS_GCC
  1925. return (Type) __sync_add_and_fetch (&value, amountToAdd);
  1926. #endif
  1927. }
  1928. template <typename Type>
  1929. inline Type Atomic<Type>::operator-= (const Type amountToSubtract) noexcept
  1930. {
  1931. return operator+= (juce_negate (amountToSubtract));
  1932. }
  1933. template <typename Type>
  1934. inline Type Atomic<Type>::operator++() noexcept
  1935. {
  1936. #if JUCE_ATOMICS_MAC
  1937. return sizeof (Type) == 4 ? (Type) OSAtomicIncrement32Barrier ((JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1938. : (Type) OSAtomicIncrement64Barrier ((JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1939. #elif JUCE_ATOMICS_WINDOWS
  1940. return sizeof (Type) == 4 ? (Type) juce_InterlockedIncrement ((volatile long*) &value)
  1941. : (Type) juce_InterlockedIncrement64 ((volatile __int64*) &value);
  1942. #elif JUCE_ATOMICS_ANDROID
  1943. return (Type) (__atomic_inc ((volatile int*) &value) + 1);
  1944. #elif JUCE_ATOMICS_GCC
  1945. return (Type) __sync_add_and_fetch (&value, 1);
  1946. #endif
  1947. }
  1948. template <typename Type>
  1949. inline Type Atomic<Type>::operator--() noexcept
  1950. {
  1951. #if JUCE_ATOMICS_MAC
  1952. return sizeof (Type) == 4 ? (Type) OSAtomicDecrement32Barrier ((JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1953. : (Type) OSAtomicDecrement64Barrier ((JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1954. #elif JUCE_ATOMICS_WINDOWS
  1955. return sizeof (Type) == 4 ? (Type) juce_InterlockedDecrement ((volatile long*) &value)
  1956. : (Type) juce_InterlockedDecrement64 ((volatile __int64*) &value);
  1957. #elif JUCE_ATOMICS_ANDROID
  1958. return (Type) (__atomic_dec ((volatile int*) &value) - 1);
  1959. #elif JUCE_ATOMICS_GCC
  1960. return (Type) __sync_add_and_fetch (&value, -1);
  1961. #endif
  1962. }
  1963. template <typename Type>
  1964. inline bool Atomic<Type>::compareAndSetBool (const Type newValue, const Type valueToCompare) noexcept
  1965. {
  1966. #if JUCE_ATOMICS_MAC
  1967. return sizeof (Type) == 4 ? OSAtomicCompareAndSwap32Barrier ((int32_t) castTo32Bit (valueToCompare), (int32_t) castTo32Bit (newValue), (JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1968. : OSAtomicCompareAndSwap64Barrier ((int64_t) castTo64Bit (valueToCompare), (int64_t) castTo64Bit (newValue), (JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1969. #elif JUCE_ATOMICS_WINDOWS
  1970. return compareAndSetValue (newValue, valueToCompare) == valueToCompare;
  1971. #elif JUCE_ATOMICS_ANDROID
  1972. return __atomic_cmpxchg (castTo32Bit (valueToCompare), castTo32Bit (newValue), (volatile int*) &value) == 0;
  1973. #elif JUCE_ATOMICS_GCC
  1974. return sizeof (Type) == 4 ? __sync_bool_compare_and_swap ((volatile int32*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue))
  1975. : __sync_bool_compare_and_swap ((volatile int64*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue));
  1976. #endif
  1977. }
  1978. template <typename Type>
  1979. inline Type Atomic<Type>::compareAndSetValue (const Type newValue, const Type valueToCompare) noexcept
  1980. {
  1981. #if JUCE_ATOMICS_MAC || JUCE_ATOMICS_ANDROID
  1982. for (;;) // Annoying workaround for only having a bool CAS operation..
  1983. {
  1984. if (compareAndSetBool (newValue, valueToCompare))
  1985. return valueToCompare;
  1986. const Type result = value;
  1987. if (result != valueToCompare)
  1988. return result;
  1989. }
  1990. #elif JUCE_ATOMICS_WINDOWS
  1991. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedCompareExchange ((volatile long*) &value, (long) castTo32Bit (newValue), (long) castTo32Bit (valueToCompare)))
  1992. : castFrom64Bit ((int64) juce_InterlockedCompareExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue), (__int64) castTo64Bit (valueToCompare)));
  1993. #elif JUCE_ATOMICS_GCC
  1994. return sizeof (Type) == 4 ? castFrom32Bit ((int32) __sync_val_compare_and_swap ((volatile int32*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue)))
  1995. : castFrom64Bit ((int64) __sync_val_compare_and_swap ((volatile int64*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue)));
  1996. #endif
  1997. }
  1998. template <typename Type>
  1999. inline void Atomic<Type>::memoryBarrier() noexcept
  2000. {
  2001. #if JUCE_ATOMICS_MAC
  2002. OSMemoryBarrier();
  2003. #elif JUCE_ATOMICS_GCC
  2004. __sync_synchronize();
  2005. #elif JUCE_ATOMICS_WINDOWS
  2006. juce_MemoryBarrier();
  2007. #endif
  2008. }
  2009. #if JUCE_MSVC
  2010. #pragma warning (pop)
  2011. #endif
  2012. #endif // __JUCE_ATOMIC_JUCEHEADER__
  2013. /*** End of inlined file: juce_Atomic.h ***/
  2014. /*** Start of inlined file: juce_CharPointer_UTF8.h ***/
  2015. #ifndef __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  2016. #define __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  2017. /**
  2018. Wraps a pointer to a null-terminated UTF-8 character string, and provides
  2019. various methods to operate on the data.
  2020. @see CharPointer_UTF16, CharPointer_UTF32
  2021. */
  2022. class CharPointer_UTF8
  2023. {
  2024. public:
  2025. typedef char CharType;
  2026. inline explicit CharPointer_UTF8 (const CharType* const rawPointer) noexcept
  2027. : data (const_cast <CharType*> (rawPointer))
  2028. {
  2029. }
  2030. inline CharPointer_UTF8 (const CharPointer_UTF8& other) noexcept
  2031. : data (other.data)
  2032. {
  2033. }
  2034. inline CharPointer_UTF8& operator= (const CharPointer_UTF8& other) noexcept
  2035. {
  2036. data = other.data;
  2037. return *this;
  2038. }
  2039. inline CharPointer_UTF8& operator= (const CharType* text) noexcept
  2040. {
  2041. data = const_cast <CharType*> (text);
  2042. return *this;
  2043. }
  2044. /** This is a pointer comparison, it doesn't compare the actual text. */
  2045. inline bool operator== (const CharPointer_UTF8& other) const noexcept { return data == other.data; }
  2046. inline bool operator!= (const CharPointer_UTF8& other) const noexcept { return data != other.data; }
  2047. inline bool operator<= (const CharPointer_UTF8& other) const noexcept { return data <= other.data; }
  2048. inline bool operator< (const CharPointer_UTF8& other) const noexcept { return data < other.data; }
  2049. inline bool operator>= (const CharPointer_UTF8& other) const noexcept { return data >= other.data; }
  2050. inline bool operator> (const CharPointer_UTF8& other) const noexcept { return data > other.data; }
  2051. /** Returns the address that this pointer is pointing to. */
  2052. inline CharType* getAddress() const noexcept { return data; }
  2053. /** Returns the address that this pointer is pointing to. */
  2054. inline operator const CharType*() const noexcept { return data; }
  2055. /** Returns true if this pointer is pointing to a null character. */
  2056. inline bool isEmpty() const noexcept { return *data == 0; }
  2057. /** Returns the unicode character that this pointer is pointing to. */
  2058. juce_wchar operator*() const noexcept
  2059. {
  2060. const signed char byte = (signed char) *data;
  2061. if (byte >= 0)
  2062. return byte;
  2063. uint32 n = (uint32) (uint8) byte;
  2064. uint32 mask = 0x7f;
  2065. uint32 bit = 0x40;
  2066. size_t numExtraValues = 0;
  2067. while ((n & bit) != 0 && bit > 0x10)
  2068. {
  2069. mask >>= 1;
  2070. ++numExtraValues;
  2071. bit >>= 1;
  2072. }
  2073. n &= mask;
  2074. for (size_t i = 1; i <= numExtraValues; ++i)
  2075. {
  2076. const juce_wchar nextByte = data [i];
  2077. if ((nextByte & 0xc0) != 0x80)
  2078. break;
  2079. n <<= 6;
  2080. n |= (nextByte & 0x3f);
  2081. }
  2082. return (juce_wchar) n;
  2083. }
  2084. /** Moves this pointer along to the next character in the string. */
  2085. CharPointer_UTF8& operator++() noexcept
  2086. {
  2087. const signed char n = (signed char) *data++;
  2088. if (n < 0)
  2089. {
  2090. juce_wchar bit = 0x40;
  2091. while ((n & bit) != 0 && bit > 0x8)
  2092. {
  2093. ++data;
  2094. bit >>= 1;
  2095. }
  2096. }
  2097. return *this;
  2098. }
  2099. /** Moves this pointer back to the previous character in the string. */
  2100. CharPointer_UTF8& operator--() noexcept
  2101. {
  2102. const char n = *--data;
  2103. if ((n & 0xc0) == 0xc0)
  2104. {
  2105. int count = 3;
  2106. do
  2107. {
  2108. --data;
  2109. }
  2110. while ((*data & 0xc0) == 0xc0 && --count >= 0);
  2111. }
  2112. return *this;
  2113. }
  2114. /** Returns the character that this pointer is currently pointing to, and then
  2115. advances the pointer to point to the next character. */
  2116. juce_wchar getAndAdvance() noexcept
  2117. {
  2118. const signed char byte = (signed char) *data++;
  2119. if (byte >= 0)
  2120. return byte;
  2121. uint32 n = (uint32) (uint8) byte;
  2122. uint32 mask = 0x7f;
  2123. uint32 bit = 0x40;
  2124. int numExtraValues = 0;
  2125. while ((n & bit) != 0 && bit > 0x8)
  2126. {
  2127. mask >>= 1;
  2128. ++numExtraValues;
  2129. bit >>= 1;
  2130. }
  2131. n &= mask;
  2132. while (--numExtraValues >= 0)
  2133. {
  2134. const uint32 nextByte = (uint32) (uint8) *data++;
  2135. if ((nextByte & 0xc0) != 0x80)
  2136. break;
  2137. n <<= 6;
  2138. n |= (nextByte & 0x3f);
  2139. }
  2140. return (juce_wchar) n;
  2141. }
  2142. /** Moves this pointer along to the next character in the string. */
  2143. CharPointer_UTF8 operator++ (int) noexcept
  2144. {
  2145. CharPointer_UTF8 temp (*this);
  2146. ++*this;
  2147. return temp;
  2148. }
  2149. /** Moves this pointer forwards by the specified number of characters. */
  2150. void operator+= (int numToSkip) noexcept
  2151. {
  2152. if (numToSkip < 0)
  2153. {
  2154. while (++numToSkip <= 0)
  2155. --*this;
  2156. }
  2157. else
  2158. {
  2159. while (--numToSkip >= 0)
  2160. ++*this;
  2161. }
  2162. }
  2163. /** Moves this pointer backwards by the specified number of characters. */
  2164. void operator-= (int numToSkip) noexcept
  2165. {
  2166. operator+= (-numToSkip);
  2167. }
  2168. /** Returns the character at a given character index from the start of the string. */
  2169. juce_wchar operator[] (int characterIndex) const noexcept
  2170. {
  2171. CharPointer_UTF8 p (*this);
  2172. p += characterIndex;
  2173. return *p;
  2174. }
  2175. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  2176. CharPointer_UTF8 operator+ (int numToSkip) const noexcept
  2177. {
  2178. CharPointer_UTF8 p (*this);
  2179. p += numToSkip;
  2180. return p;
  2181. }
  2182. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  2183. CharPointer_UTF8 operator- (int numToSkip) const noexcept
  2184. {
  2185. CharPointer_UTF8 p (*this);
  2186. p += -numToSkip;
  2187. return p;
  2188. }
  2189. /** Returns the number of characters in this string. */
  2190. size_t length() const noexcept
  2191. {
  2192. const CharType* d = data;
  2193. size_t count = 0;
  2194. for (;;)
  2195. {
  2196. const uint32 n = (uint32) (uint8) *d++;
  2197. if ((n & 0x80) != 0)
  2198. {
  2199. uint32 bit = 0x40;
  2200. while ((n & bit) != 0)
  2201. {
  2202. ++d;
  2203. bit >>= 1;
  2204. if (bit == 0)
  2205. break; // illegal utf-8 sequence
  2206. }
  2207. }
  2208. else if (n == 0)
  2209. break;
  2210. ++count;
  2211. }
  2212. return count;
  2213. }
  2214. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  2215. size_t lengthUpTo (const size_t maxCharsToCount) const noexcept
  2216. {
  2217. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  2218. }
  2219. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  2220. size_t lengthUpTo (const CharPointer_UTF8& end) const noexcept
  2221. {
  2222. return CharacterFunctions::lengthUpTo (*this, end);
  2223. }
  2224. /** Returns the number of bytes that are used to represent this string.
  2225. This includes the terminating null character.
  2226. */
  2227. size_t sizeInBytes() const noexcept
  2228. {
  2229. return strlen (data) + 1;
  2230. }
  2231. /** Returns the number of bytes that would be needed to represent the given
  2232. unicode character in this encoding format.
  2233. */
  2234. static size_t getBytesRequiredFor (const juce_wchar charToWrite) noexcept
  2235. {
  2236. size_t num = 1;
  2237. const uint32 c = (uint32) charToWrite;
  2238. if (c >= 0x80)
  2239. {
  2240. ++num;
  2241. if (c >= 0x800)
  2242. {
  2243. ++num;
  2244. if (c >= 0x10000)
  2245. ++num;
  2246. }
  2247. }
  2248. return num;
  2249. }
  2250. /** Returns the number of bytes that would be needed to represent the given
  2251. string in this encoding format.
  2252. The value returned does NOT include the terminating null character.
  2253. */
  2254. template <class CharPointer>
  2255. static size_t getBytesRequiredFor (CharPointer text) noexcept
  2256. {
  2257. size_t count = 0;
  2258. juce_wchar n;
  2259. while ((n = text.getAndAdvance()) != 0)
  2260. count += getBytesRequiredFor (n);
  2261. return count;
  2262. }
  2263. /** Returns a pointer to the null character that terminates this string. */
  2264. CharPointer_UTF8 findTerminatingNull() const noexcept
  2265. {
  2266. return CharPointer_UTF8 (data + strlen (data));
  2267. }
  2268. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  2269. void write (const juce_wchar charToWrite) noexcept
  2270. {
  2271. const uint32 c = (uint32) charToWrite;
  2272. if (c >= 0x80)
  2273. {
  2274. int numExtraBytes = 1;
  2275. if (c >= 0x800)
  2276. {
  2277. ++numExtraBytes;
  2278. if (c >= 0x10000)
  2279. ++numExtraBytes;
  2280. }
  2281. *data++ = (CharType) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  2282. while (--numExtraBytes >= 0)
  2283. *data++ = (CharType) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  2284. }
  2285. else
  2286. {
  2287. *data++ = (CharType) c;
  2288. }
  2289. }
  2290. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  2291. inline void writeNull() const noexcept
  2292. {
  2293. *data = 0;
  2294. }
  2295. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2296. template <typename CharPointer>
  2297. void writeAll (const CharPointer& src) noexcept
  2298. {
  2299. CharacterFunctions::copyAll (*this, src);
  2300. }
  2301. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2302. void writeAll (const CharPointer_UTF8& src) noexcept
  2303. {
  2304. const CharType* s = src.data;
  2305. while ((*data = *s) != 0)
  2306. {
  2307. ++data;
  2308. ++s;
  2309. }
  2310. }
  2311. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2312. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  2313. to the destination buffer before stopping.
  2314. */
  2315. template <typename CharPointer>
  2316. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) noexcept
  2317. {
  2318. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  2319. }
  2320. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2321. The maxChars parameter specifies the maximum number of characters that can be
  2322. written to the destination buffer before stopping (including the terminating null).
  2323. */
  2324. template <typename CharPointer>
  2325. void writeWithCharLimit (const CharPointer& src, const int maxChars) noexcept
  2326. {
  2327. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  2328. }
  2329. /** Compares this string with another one. */
  2330. template <typename CharPointer>
  2331. int compare (const CharPointer& other) const noexcept
  2332. {
  2333. return CharacterFunctions::compare (*this, other);
  2334. }
  2335. /** Compares this string with another one, up to a specified number of characters. */
  2336. template <typename CharPointer>
  2337. int compareUpTo (const CharPointer& other, const int maxChars) const noexcept
  2338. {
  2339. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  2340. }
  2341. /** Compares this string with another one. */
  2342. template <typename CharPointer>
  2343. int compareIgnoreCase (const CharPointer& other) const noexcept
  2344. {
  2345. return CharacterFunctions::compareIgnoreCase (*this, other);
  2346. }
  2347. /** Compares this string with another one. */
  2348. int compareIgnoreCase (const CharPointer_UTF8& other) const noexcept
  2349. {
  2350. #if JUCE_WINDOWS
  2351. return stricmp (data, other.data);
  2352. #else
  2353. return strcasecmp (data, other.data);
  2354. #endif
  2355. }
  2356. /** Compares this string with another one, up to a specified number of characters. */
  2357. template <typename CharPointer>
  2358. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const noexcept
  2359. {
  2360. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  2361. }
  2362. /** Compares this string with another one, up to a specified number of characters. */
  2363. int compareIgnoreCaseUpTo (const CharPointer_UTF8& other, const int maxChars) const noexcept
  2364. {
  2365. #if JUCE_WINDOWS
  2366. return strnicmp (data, other.data, maxChars);
  2367. #else
  2368. return strncasecmp (data, other.data, maxChars);
  2369. #endif
  2370. }
  2371. /** Returns the character index of a substring, or -1 if it isn't found. */
  2372. template <typename CharPointer>
  2373. int indexOf (const CharPointer& stringToFind) const noexcept
  2374. {
  2375. return CharacterFunctions::indexOf (*this, stringToFind);
  2376. }
  2377. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2378. int indexOf (const juce_wchar charToFind) const noexcept
  2379. {
  2380. return CharacterFunctions::indexOfChar (*this, charToFind);
  2381. }
  2382. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2383. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const noexcept
  2384. {
  2385. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  2386. : CharacterFunctions::indexOfChar (*this, charToFind);
  2387. }
  2388. /** Returns true if the first character of this string is whitespace. */
  2389. bool isWhitespace() const noexcept { return *data == ' ' || (*data <= 13 && *data >= 9); }
  2390. /** Returns true if the first character of this string is a digit. */
  2391. bool isDigit() const noexcept { return *data >= '0' && *data <= '9'; }
  2392. /** Returns true if the first character of this string is a letter. */
  2393. bool isLetter() const noexcept { return CharacterFunctions::isLetter (operator*()) != 0; }
  2394. /** Returns true if the first character of this string is a letter or digit. */
  2395. bool isLetterOrDigit() const noexcept { return CharacterFunctions::isLetterOrDigit (operator*()) != 0; }
  2396. /** Returns true if the first character of this string is upper-case. */
  2397. bool isUpperCase() const noexcept { return CharacterFunctions::isUpperCase (operator*()) != 0; }
  2398. /** Returns true if the first character of this string is lower-case. */
  2399. bool isLowerCase() const noexcept { return CharacterFunctions::isLowerCase (operator*()) != 0; }
  2400. /** Returns an upper-case version of the first character of this string. */
  2401. juce_wchar toUpperCase() const noexcept { return CharacterFunctions::toUpperCase (operator*()); }
  2402. /** Returns a lower-case version of the first character of this string. */
  2403. juce_wchar toLowerCase() const noexcept { return CharacterFunctions::toLowerCase (operator*()); }
  2404. /** Parses this string as a 32-bit integer. */
  2405. int getIntValue32() const noexcept { return atoi (data); }
  2406. /** Parses this string as a 64-bit integer. */
  2407. int64 getIntValue64() const noexcept
  2408. {
  2409. #if JUCE_LINUX || JUCE_ANDROID
  2410. return atoll (data);
  2411. #elif JUCE_WINDOWS
  2412. return _atoi64 (data);
  2413. #else
  2414. return CharacterFunctions::getIntValue <int64, CharPointer_UTF8> (*this);
  2415. #endif
  2416. }
  2417. /** Parses this string as a floating point double. */
  2418. double getDoubleValue() const noexcept { return CharacterFunctions::getDoubleValue (*this); }
  2419. /** Returns the first non-whitespace character in the string. */
  2420. CharPointer_UTF8 findEndOfWhitespace() const noexcept { return CharacterFunctions::findEndOfWhitespace (*this); }
  2421. /** Returns true if the given unicode character can be represented in this encoding. */
  2422. static bool canRepresent (juce_wchar character) noexcept
  2423. {
  2424. return ((unsigned int) character) < (unsigned int) 0x10ffff;
  2425. }
  2426. /** Returns true if this data contains a valid string in this encoding. */
  2427. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  2428. {
  2429. while (--maxBytesToRead >= 0 && *dataToTest != 0)
  2430. {
  2431. const signed char byte = (signed char) *dataToTest;
  2432. if (byte < 0)
  2433. {
  2434. uint32 n = (uint32) (uint8) byte;
  2435. uint32 mask = 0x7f;
  2436. uint32 bit = 0x40;
  2437. int numExtraValues = 0;
  2438. while ((n & bit) != 0)
  2439. {
  2440. if (bit <= 0x10)
  2441. return false;
  2442. mask >>= 1;
  2443. ++numExtraValues;
  2444. bit >>= 1;
  2445. }
  2446. n &= mask;
  2447. while (--numExtraValues >= 0)
  2448. {
  2449. const uint32 nextByte = (uint32) (uint8) *dataToTest++;
  2450. if ((nextByte & 0xc0) != 0x80)
  2451. return false;
  2452. }
  2453. }
  2454. }
  2455. return true;
  2456. }
  2457. /** Atomically swaps this pointer for a new value, returning the previous value. */
  2458. CharPointer_UTF8 atomicSwap (const CharPointer_UTF8& newValue)
  2459. {
  2460. return CharPointer_UTF8 (reinterpret_cast <Atomic<CharType*>&> (data).exchange (newValue.data));
  2461. }
  2462. /** These values are the byte-order-mark (BOM) values for a UTF-8 stream. */
  2463. enum
  2464. {
  2465. byteOrderMark1 = 0xef,
  2466. byteOrderMark2 = 0xbb,
  2467. byteOrderMark3 = 0xbf
  2468. };
  2469. private:
  2470. CharType* data;
  2471. };
  2472. #endif // __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  2473. /*** End of inlined file: juce_CharPointer_UTF8.h ***/
  2474. /*** Start of inlined file: juce_CharPointer_UTF16.h ***/
  2475. #ifndef __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  2476. #define __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  2477. /**
  2478. Wraps a pointer to a null-terminated UTF-16 character string, and provides
  2479. various methods to operate on the data.
  2480. @see CharPointer_UTF8, CharPointer_UTF32
  2481. */
  2482. class CharPointer_UTF16
  2483. {
  2484. public:
  2485. #if JUCE_NATIVE_WCHAR_IS_UTF16
  2486. typedef wchar_t CharType;
  2487. #else
  2488. typedef int16 CharType;
  2489. #endif
  2490. inline explicit CharPointer_UTF16 (const CharType* const rawPointer) noexcept
  2491. : data (const_cast <CharType*> (rawPointer))
  2492. {
  2493. }
  2494. inline CharPointer_UTF16 (const CharPointer_UTF16& other) noexcept
  2495. : data (other.data)
  2496. {
  2497. }
  2498. inline CharPointer_UTF16& operator= (const CharPointer_UTF16& other) noexcept
  2499. {
  2500. data = other.data;
  2501. return *this;
  2502. }
  2503. inline CharPointer_UTF16& operator= (const CharType* text) noexcept
  2504. {
  2505. data = const_cast <CharType*> (text);
  2506. return *this;
  2507. }
  2508. /** This is a pointer comparison, it doesn't compare the actual text. */
  2509. inline bool operator== (const CharPointer_UTF16& other) const noexcept { return data == other.data; }
  2510. inline bool operator!= (const CharPointer_UTF16& other) const noexcept { return data != other.data; }
  2511. inline bool operator<= (const CharPointer_UTF16& other) const noexcept { return data <= other.data; }
  2512. inline bool operator< (const CharPointer_UTF16& other) const noexcept { return data < other.data; }
  2513. inline bool operator>= (const CharPointer_UTF16& other) const noexcept { return data >= other.data; }
  2514. inline bool operator> (const CharPointer_UTF16& other) const noexcept { return data > other.data; }
  2515. /** Returns the address that this pointer is pointing to. */
  2516. inline CharType* getAddress() const noexcept { return data; }
  2517. /** Returns the address that this pointer is pointing to. */
  2518. inline operator const CharType*() const noexcept { return data; }
  2519. /** Returns true if this pointer is pointing to a null character. */
  2520. inline bool isEmpty() const noexcept { return *data == 0; }
  2521. /** Returns the unicode character that this pointer is pointing to. */
  2522. juce_wchar operator*() const noexcept
  2523. {
  2524. uint32 n = (uint32) (uint16) *data;
  2525. if (n >= 0xd800 && n <= 0xdfff && ((uint32) (uint16) data[1]) >= 0xdc00)
  2526. n = 0x10000 + (((n - 0xd800) << 10) | (((uint32) (uint16) data[1]) - 0xdc00));
  2527. return (juce_wchar) n;
  2528. }
  2529. /** Moves this pointer along to the next character in the string. */
  2530. CharPointer_UTF16& operator++() noexcept
  2531. {
  2532. const juce_wchar n = *data++;
  2533. if (n >= 0xd800 && n <= 0xdfff && ((uint32) (uint16) *data) >= 0xdc00)
  2534. ++data;
  2535. return *this;
  2536. }
  2537. /** Moves this pointer back to the previous character in the string. */
  2538. CharPointer_UTF16& operator--() noexcept
  2539. {
  2540. const juce_wchar n = *--data;
  2541. if (n >= 0xdc00 && n <= 0xdfff)
  2542. --data;
  2543. return *this;
  2544. }
  2545. /** Returns the character that this pointer is currently pointing to, and then
  2546. advances the pointer to point to the next character. */
  2547. juce_wchar getAndAdvance() noexcept
  2548. {
  2549. uint32 n = (uint32) (uint16) *data++;
  2550. if (n >= 0xd800 && n <= 0xdfff && ((uint32) (uint16) *data) >= 0xdc00)
  2551. n = 0x10000 + ((((n - 0xd800) << 10) | (((uint32) (uint16) *data++) - 0xdc00)));
  2552. return (juce_wchar) n;
  2553. }
  2554. /** Moves this pointer along to the next character in the string. */
  2555. CharPointer_UTF16 operator++ (int) noexcept
  2556. {
  2557. CharPointer_UTF16 temp (*this);
  2558. ++*this;
  2559. return temp;
  2560. }
  2561. /** Moves this pointer forwards by the specified number of characters. */
  2562. void operator+= (int numToSkip) noexcept
  2563. {
  2564. if (numToSkip < 0)
  2565. {
  2566. while (++numToSkip <= 0)
  2567. --*this;
  2568. }
  2569. else
  2570. {
  2571. while (--numToSkip >= 0)
  2572. ++*this;
  2573. }
  2574. }
  2575. /** Moves this pointer backwards by the specified number of characters. */
  2576. void operator-= (int numToSkip) noexcept
  2577. {
  2578. operator+= (-numToSkip);
  2579. }
  2580. /** Returns the character at a given character index from the start of the string. */
  2581. juce_wchar operator[] (const int characterIndex) const noexcept
  2582. {
  2583. CharPointer_UTF16 p (*this);
  2584. p += characterIndex;
  2585. return *p;
  2586. }
  2587. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  2588. CharPointer_UTF16 operator+ (const int numToSkip) const noexcept
  2589. {
  2590. CharPointer_UTF16 p (*this);
  2591. p += numToSkip;
  2592. return p;
  2593. }
  2594. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  2595. CharPointer_UTF16 operator- (const int numToSkip) const noexcept
  2596. {
  2597. CharPointer_UTF16 p (*this);
  2598. p += -numToSkip;
  2599. return p;
  2600. }
  2601. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  2602. void write (juce_wchar charToWrite) noexcept
  2603. {
  2604. if (charToWrite >= 0x10000)
  2605. {
  2606. charToWrite -= 0x10000;
  2607. *data++ = (CharType) (0xd800 + (charToWrite >> 10));
  2608. *data++ = (CharType) (0xdc00 + (charToWrite & 0x3ff));
  2609. }
  2610. else
  2611. {
  2612. *data++ = (CharType) charToWrite;
  2613. }
  2614. }
  2615. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  2616. inline void writeNull() const noexcept
  2617. {
  2618. *data = 0;
  2619. }
  2620. /** Returns the number of characters in this string. */
  2621. size_t length() const noexcept
  2622. {
  2623. const CharType* d = data;
  2624. size_t count = 0;
  2625. for (;;)
  2626. {
  2627. const int n = *d++;
  2628. if (n >= 0xd800 && n <= 0xdfff)
  2629. {
  2630. if (*d++ == 0)
  2631. break;
  2632. }
  2633. else if (n == 0)
  2634. break;
  2635. ++count;
  2636. }
  2637. return count;
  2638. }
  2639. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  2640. size_t lengthUpTo (const size_t maxCharsToCount) const noexcept
  2641. {
  2642. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  2643. }
  2644. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  2645. size_t lengthUpTo (const CharPointer_UTF16& end) const noexcept
  2646. {
  2647. return CharacterFunctions::lengthUpTo (*this, end);
  2648. }
  2649. /** Returns the number of bytes that are used to represent this string.
  2650. This includes the terminating null character.
  2651. */
  2652. size_t sizeInBytes() const noexcept
  2653. {
  2654. return sizeof (CharType) * (findNullIndex (data) + 1);
  2655. }
  2656. /** Returns the number of bytes that would be needed to represent the given
  2657. unicode character in this encoding format.
  2658. */
  2659. static size_t getBytesRequiredFor (const juce_wchar charToWrite) noexcept
  2660. {
  2661. return (charToWrite >= 0x10000) ? (sizeof (CharType) * 2) : sizeof (CharType);
  2662. }
  2663. /** Returns the number of bytes that would be needed to represent the given
  2664. string in this encoding format.
  2665. The value returned does NOT include the terminating null character.
  2666. */
  2667. template <class CharPointer>
  2668. static size_t getBytesRequiredFor (CharPointer text) noexcept
  2669. {
  2670. size_t count = 0;
  2671. juce_wchar n;
  2672. while ((n = text.getAndAdvance()) != 0)
  2673. count += getBytesRequiredFor (n);
  2674. return count;
  2675. }
  2676. /** Returns a pointer to the null character that terminates this string. */
  2677. CharPointer_UTF16 findTerminatingNull() const noexcept
  2678. {
  2679. const CharType* t = data;
  2680. while (*t != 0)
  2681. ++t;
  2682. return CharPointer_UTF16 (t);
  2683. }
  2684. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2685. template <typename CharPointer>
  2686. void writeAll (const CharPointer& src) noexcept
  2687. {
  2688. CharacterFunctions::copyAll (*this, src);
  2689. }
  2690. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2691. void writeAll (const CharPointer_UTF16& src) noexcept
  2692. {
  2693. const CharType* s = src.data;
  2694. while ((*data = *s) != 0)
  2695. {
  2696. ++data;
  2697. ++s;
  2698. }
  2699. }
  2700. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2701. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  2702. to the destination buffer before stopping.
  2703. */
  2704. template <typename CharPointer>
  2705. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) noexcept
  2706. {
  2707. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  2708. }
  2709. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2710. The maxChars parameter specifies the maximum number of characters that can be
  2711. written to the destination buffer before stopping (including the terminating null).
  2712. */
  2713. template <typename CharPointer>
  2714. void writeWithCharLimit (const CharPointer& src, const int maxChars) noexcept
  2715. {
  2716. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  2717. }
  2718. /** Compares this string with another one. */
  2719. template <typename CharPointer>
  2720. int compare (const CharPointer& other) const noexcept
  2721. {
  2722. return CharacterFunctions::compare (*this, other);
  2723. }
  2724. /** Compares this string with another one, up to a specified number of characters. */
  2725. template <typename CharPointer>
  2726. int compareUpTo (const CharPointer& other, const int maxChars) const noexcept
  2727. {
  2728. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  2729. }
  2730. /** Compares this string with another one. */
  2731. template <typename CharPointer>
  2732. int compareIgnoreCase (const CharPointer& other) const noexcept
  2733. {
  2734. return CharacterFunctions::compareIgnoreCase (*this, other);
  2735. }
  2736. /** Compares this string with another one, up to a specified number of characters. */
  2737. template <typename CharPointer>
  2738. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const noexcept
  2739. {
  2740. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  2741. }
  2742. #if JUCE_WINDOWS && ! DOXYGEN
  2743. int compareIgnoreCase (const CharPointer_UTF16& other) const noexcept
  2744. {
  2745. return _wcsicmp (data, other.data);
  2746. }
  2747. int compareIgnoreCaseUpTo (const CharPointer_UTF16& other, int maxChars) const noexcept
  2748. {
  2749. return _wcsnicmp (data, other.data, maxChars);
  2750. }
  2751. int indexOf (const CharPointer_UTF16& stringToFind) const noexcept
  2752. {
  2753. const CharType* const t = wcsstr (data, stringToFind.getAddress());
  2754. return t == nullptr ? -1 : (int) (t - data);
  2755. }
  2756. #endif
  2757. /** Returns the character index of a substring, or -1 if it isn't found. */
  2758. template <typename CharPointer>
  2759. int indexOf (const CharPointer& stringToFind) const noexcept
  2760. {
  2761. return CharacterFunctions::indexOf (*this, stringToFind);
  2762. }
  2763. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2764. int indexOf (const juce_wchar charToFind) const noexcept
  2765. {
  2766. return CharacterFunctions::indexOfChar (*this, charToFind);
  2767. }
  2768. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2769. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const noexcept
  2770. {
  2771. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  2772. : CharacterFunctions::indexOfChar (*this, charToFind);
  2773. }
  2774. /** Returns true if the first character of this string is whitespace. */
  2775. bool isWhitespace() const noexcept { return CharacterFunctions::isWhitespace (operator*()) != 0; }
  2776. /** Returns true if the first character of this string is a digit. */
  2777. bool isDigit() const noexcept { return CharacterFunctions::isDigit (operator*()) != 0; }
  2778. /** Returns true if the first character of this string is a letter. */
  2779. bool isLetter() const noexcept { return CharacterFunctions::isLetter (operator*()) != 0; }
  2780. /** Returns true if the first character of this string is a letter or digit. */
  2781. bool isLetterOrDigit() const noexcept { return CharacterFunctions::isLetterOrDigit (operator*()) != 0; }
  2782. /** Returns true if the first character of this string is upper-case. */
  2783. bool isUpperCase() const noexcept { return CharacterFunctions::isUpperCase (operator*()) != 0; }
  2784. /** Returns true if the first character of this string is lower-case. */
  2785. bool isLowerCase() const noexcept { return CharacterFunctions::isLowerCase (operator*()) != 0; }
  2786. /** Returns an upper-case version of the first character of this string. */
  2787. juce_wchar toUpperCase() const noexcept { return CharacterFunctions::toUpperCase (operator*()); }
  2788. /** Returns a lower-case version of the first character of this string. */
  2789. juce_wchar toLowerCase() const noexcept { return CharacterFunctions::toLowerCase (operator*()); }
  2790. /** Parses this string as a 32-bit integer. */
  2791. int getIntValue32() const noexcept
  2792. {
  2793. #if JUCE_WINDOWS
  2794. return _wtoi (data);
  2795. #else
  2796. return CharacterFunctions::getIntValue <int, CharPointer_UTF16> (*this);
  2797. #endif
  2798. }
  2799. /** Parses this string as a 64-bit integer. */
  2800. int64 getIntValue64() const noexcept
  2801. {
  2802. #if JUCE_WINDOWS
  2803. return _wtoi64 (data);
  2804. #else
  2805. return CharacterFunctions::getIntValue <int64, CharPointer_UTF16> (*this);
  2806. #endif
  2807. }
  2808. /** Parses this string as a floating point double. */
  2809. double getDoubleValue() const noexcept { return CharacterFunctions::getDoubleValue (*this); }
  2810. /** Returns the first non-whitespace character in the string. */
  2811. CharPointer_UTF16 findEndOfWhitespace() const noexcept { return CharacterFunctions::findEndOfWhitespace (*this); }
  2812. /** Returns true if the given unicode character can be represented in this encoding. */
  2813. static bool canRepresent (juce_wchar character) noexcept
  2814. {
  2815. return ((unsigned int) character) < (unsigned int) 0x10ffff
  2816. && (((unsigned int) character) < 0xd800 || ((unsigned int) character) > 0xdfff);
  2817. }
  2818. /** Returns true if this data contains a valid string in this encoding. */
  2819. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  2820. {
  2821. maxBytesToRead /= sizeof (CharType);
  2822. while (--maxBytesToRead >= 0 && *dataToTest != 0)
  2823. {
  2824. const uint32 n = (uint32) (uint16) *dataToTest++;
  2825. if (n >= 0xd800)
  2826. {
  2827. if (n > 0x10ffff)
  2828. return false;
  2829. if (n <= 0xdfff)
  2830. {
  2831. if (n > 0xdc00)
  2832. return false;
  2833. const uint32 nextChar = (uint32) (uint16) *dataToTest++;
  2834. if (nextChar < 0xdc00 || nextChar > 0xdfff)
  2835. return false;
  2836. }
  2837. }
  2838. }
  2839. return true;
  2840. }
  2841. /** Atomically swaps this pointer for a new value, returning the previous value. */
  2842. CharPointer_UTF16 atomicSwap (const CharPointer_UTF16& newValue)
  2843. {
  2844. return CharPointer_UTF16 (reinterpret_cast <Atomic<CharType*>&> (data).exchange (newValue.data));
  2845. }
  2846. /** These values are the byte-order-mark (BOM) values for a UTF-16 stream. */
  2847. enum
  2848. {
  2849. byteOrderMarkBE1 = 0xfe,
  2850. byteOrderMarkBE2 = 0xff,
  2851. byteOrderMarkLE1 = 0xff,
  2852. byteOrderMarkLE2 = 0xfe
  2853. };
  2854. private:
  2855. CharType* data;
  2856. static int findNullIndex (const CharType* const t) noexcept
  2857. {
  2858. int n = 0;
  2859. while (t[n] != 0)
  2860. ++n;
  2861. return n;
  2862. }
  2863. };
  2864. #endif // __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  2865. /*** End of inlined file: juce_CharPointer_UTF16.h ***/
  2866. /*** Start of inlined file: juce_CharPointer_UTF32.h ***/
  2867. #ifndef __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  2868. #define __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  2869. /**
  2870. Wraps a pointer to a null-terminated UTF-32 character string, and provides
  2871. various methods to operate on the data.
  2872. @see CharPointer_UTF8, CharPointer_UTF16
  2873. */
  2874. class CharPointer_UTF32
  2875. {
  2876. public:
  2877. typedef juce_wchar CharType;
  2878. inline explicit CharPointer_UTF32 (const CharType* const rawPointer) noexcept
  2879. : data (const_cast <CharType*> (rawPointer))
  2880. {
  2881. }
  2882. inline CharPointer_UTF32 (const CharPointer_UTF32& other) noexcept
  2883. : data (other.data)
  2884. {
  2885. }
  2886. inline CharPointer_UTF32& operator= (const CharPointer_UTF32& other) noexcept
  2887. {
  2888. data = other.data;
  2889. return *this;
  2890. }
  2891. inline CharPointer_UTF32& operator= (const CharType* text) noexcept
  2892. {
  2893. data = const_cast <CharType*> (text);
  2894. return *this;
  2895. }
  2896. /** This is a pointer comparison, it doesn't compare the actual text. */
  2897. inline bool operator== (const CharPointer_UTF32& other) const noexcept { return data == other.data; }
  2898. inline bool operator!= (const CharPointer_UTF32& other) const noexcept { return data != other.data; }
  2899. inline bool operator<= (const CharPointer_UTF32& other) const noexcept { return data <= other.data; }
  2900. inline bool operator< (const CharPointer_UTF32& other) const noexcept { return data < other.data; }
  2901. inline bool operator>= (const CharPointer_UTF32& other) const noexcept { return data >= other.data; }
  2902. inline bool operator> (const CharPointer_UTF32& other) const noexcept { return data > other.data; }
  2903. /** Returns the address that this pointer is pointing to. */
  2904. inline CharType* getAddress() const noexcept { return data; }
  2905. /** Returns the address that this pointer is pointing to. */
  2906. inline operator const CharType*() const noexcept { return data; }
  2907. /** Returns true if this pointer is pointing to a null character. */
  2908. inline bool isEmpty() const noexcept { return *data == 0; }
  2909. /** Returns the unicode character that this pointer is pointing to. */
  2910. inline juce_wchar operator*() const noexcept { return *data; }
  2911. /** Moves this pointer along to the next character in the string. */
  2912. inline CharPointer_UTF32& operator++() noexcept
  2913. {
  2914. ++data;
  2915. return *this;
  2916. }
  2917. /** Moves this pointer to the previous character in the string. */
  2918. inline CharPointer_UTF32& operator--() noexcept
  2919. {
  2920. --data;
  2921. return *this;
  2922. }
  2923. /** Returns the character that this pointer is currently pointing to, and then
  2924. advances the pointer to point to the next character. */
  2925. inline juce_wchar getAndAdvance() noexcept { return *data++; }
  2926. /** Moves this pointer along to the next character in the string. */
  2927. CharPointer_UTF32 operator++ (int) noexcept
  2928. {
  2929. CharPointer_UTF32 temp (*this);
  2930. ++data;
  2931. return temp;
  2932. }
  2933. /** Moves this pointer forwards by the specified number of characters. */
  2934. inline void operator+= (const int numToSkip) noexcept
  2935. {
  2936. data += numToSkip;
  2937. }
  2938. inline void operator-= (const int numToSkip) noexcept
  2939. {
  2940. data -= numToSkip;
  2941. }
  2942. /** Returns the character at a given character index from the start of the string. */
  2943. inline juce_wchar& operator[] (const int characterIndex) const noexcept
  2944. {
  2945. return data [characterIndex];
  2946. }
  2947. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  2948. CharPointer_UTF32 operator+ (const int numToSkip) const noexcept
  2949. {
  2950. return CharPointer_UTF32 (data + numToSkip);
  2951. }
  2952. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  2953. CharPointer_UTF32 operator- (const int numToSkip) const noexcept
  2954. {
  2955. return CharPointer_UTF32 (data - numToSkip);
  2956. }
  2957. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  2958. inline void write (const juce_wchar charToWrite) noexcept
  2959. {
  2960. *data++ = charToWrite;
  2961. }
  2962. inline void replaceChar (const juce_wchar newChar) noexcept
  2963. {
  2964. *data = newChar;
  2965. }
  2966. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  2967. inline void writeNull() const noexcept
  2968. {
  2969. *data = 0;
  2970. }
  2971. /** Returns the number of characters in this string. */
  2972. size_t length() const noexcept
  2973. {
  2974. #if JUCE_NATIVE_WCHAR_IS_UTF32 && ! JUCE_ANDROID
  2975. return wcslen (data);
  2976. #else
  2977. size_t n = 0;
  2978. while (data[n] != 0)
  2979. ++n;
  2980. return n;
  2981. #endif
  2982. }
  2983. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  2984. size_t lengthUpTo (const size_t maxCharsToCount) const noexcept
  2985. {
  2986. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  2987. }
  2988. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  2989. size_t lengthUpTo (const CharPointer_UTF32& end) const noexcept
  2990. {
  2991. return CharacterFunctions::lengthUpTo (*this, end);
  2992. }
  2993. /** Returns the number of bytes that are used to represent this string.
  2994. This includes the terminating null character.
  2995. */
  2996. size_t sizeInBytes() const noexcept
  2997. {
  2998. return sizeof (CharType) * (length() + 1);
  2999. }
  3000. /** Returns the number of bytes that would be needed to represent the given
  3001. unicode character in this encoding format.
  3002. */
  3003. static inline size_t getBytesRequiredFor (const juce_wchar) noexcept
  3004. {
  3005. return sizeof (CharType);
  3006. }
  3007. /** Returns the number of bytes that would be needed to represent the given
  3008. string in this encoding format.
  3009. The value returned does NOT include the terminating null character.
  3010. */
  3011. template <class CharPointer>
  3012. static size_t getBytesRequiredFor (const CharPointer& text) noexcept
  3013. {
  3014. return sizeof (CharType) * text.length();
  3015. }
  3016. /** Returns a pointer to the null character that terminates this string. */
  3017. CharPointer_UTF32 findTerminatingNull() const noexcept
  3018. {
  3019. return CharPointer_UTF32 (data + length());
  3020. }
  3021. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3022. template <typename CharPointer>
  3023. void writeAll (const CharPointer& src) noexcept
  3024. {
  3025. CharacterFunctions::copyAll (*this, src);
  3026. }
  3027. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3028. void writeAll (const CharPointer_UTF32& src) noexcept
  3029. {
  3030. const CharType* s = src.data;
  3031. while ((*data = *s) != 0)
  3032. {
  3033. ++data;
  3034. ++s;
  3035. }
  3036. }
  3037. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3038. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  3039. to the destination buffer before stopping.
  3040. */
  3041. template <typename CharPointer>
  3042. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) noexcept
  3043. {
  3044. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  3045. }
  3046. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3047. The maxChars parameter specifies the maximum number of characters that can be
  3048. written to the destination buffer before stopping (including the terminating null).
  3049. */
  3050. template <typename CharPointer>
  3051. void writeWithCharLimit (const CharPointer& src, const int maxChars) noexcept
  3052. {
  3053. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  3054. }
  3055. /** Compares this string with another one. */
  3056. template <typename CharPointer>
  3057. int compare (const CharPointer& other) const noexcept
  3058. {
  3059. return CharacterFunctions::compare (*this, other);
  3060. }
  3061. #if JUCE_NATIVE_WCHAR_IS_UTF32 && ! JUCE_ANDROID
  3062. /** Compares this string with another one. */
  3063. int compare (const CharPointer_UTF32& other) const noexcept
  3064. {
  3065. return wcscmp (data, other.data);
  3066. }
  3067. #endif
  3068. /** Compares this string with another one, up to a specified number of characters. */
  3069. template <typename CharPointer>
  3070. int compareUpTo (const CharPointer& other, const int maxChars) const noexcept
  3071. {
  3072. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  3073. }
  3074. /** Compares this string with another one. */
  3075. template <typename CharPointer>
  3076. int compareIgnoreCase (const CharPointer& other) const
  3077. {
  3078. return CharacterFunctions::compareIgnoreCase (*this, other);
  3079. }
  3080. /** Compares this string with another one, up to a specified number of characters. */
  3081. template <typename CharPointer>
  3082. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const noexcept
  3083. {
  3084. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  3085. }
  3086. /** Returns the character index of a substring, or -1 if it isn't found. */
  3087. template <typename CharPointer>
  3088. int indexOf (const CharPointer& stringToFind) const noexcept
  3089. {
  3090. return CharacterFunctions::indexOf (*this, stringToFind);
  3091. }
  3092. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3093. int indexOf (const juce_wchar charToFind) const noexcept
  3094. {
  3095. int i = 0;
  3096. while (data[i] != 0)
  3097. {
  3098. if (data[i] == charToFind)
  3099. return i;
  3100. ++i;
  3101. }
  3102. return -1;
  3103. }
  3104. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3105. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const noexcept
  3106. {
  3107. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  3108. : CharacterFunctions::indexOfChar (*this, charToFind);
  3109. }
  3110. /** Returns true if the first character of this string is whitespace. */
  3111. bool isWhitespace() const { return CharacterFunctions::isWhitespace (*data) != 0; }
  3112. /** Returns true if the first character of this string is a digit. */
  3113. bool isDigit() const { return CharacterFunctions::isDigit (*data) != 0; }
  3114. /** Returns true if the first character of this string is a letter. */
  3115. bool isLetter() const { return CharacterFunctions::isLetter (*data) != 0; }
  3116. /** Returns true if the first character of this string is a letter or digit. */
  3117. bool isLetterOrDigit() const { return CharacterFunctions::isLetterOrDigit (*data) != 0; }
  3118. /** Returns true if the first character of this string is upper-case. */
  3119. bool isUpperCase() const { return CharacterFunctions::isUpperCase (*data) != 0; }
  3120. /** Returns true if the first character of this string is lower-case. */
  3121. bool isLowerCase() const { return CharacterFunctions::isLowerCase (*data) != 0; }
  3122. /** Returns an upper-case version of the first character of this string. */
  3123. juce_wchar toUpperCase() const noexcept { return CharacterFunctions::toUpperCase (*data); }
  3124. /** Returns a lower-case version of the first character of this string. */
  3125. juce_wchar toLowerCase() const noexcept { return CharacterFunctions::toLowerCase (*data); }
  3126. /** Parses this string as a 32-bit integer. */
  3127. int getIntValue32() const noexcept { return CharacterFunctions::getIntValue <int, CharPointer_UTF32> (*this); }
  3128. /** Parses this string as a 64-bit integer. */
  3129. int64 getIntValue64() const noexcept { return CharacterFunctions::getIntValue <int64, CharPointer_UTF32> (*this); }
  3130. /** Parses this string as a floating point double. */
  3131. double getDoubleValue() const noexcept { return CharacterFunctions::getDoubleValue (*this); }
  3132. /** Returns the first non-whitespace character in the string. */
  3133. CharPointer_UTF32 findEndOfWhitespace() const noexcept { return CharacterFunctions::findEndOfWhitespace (*this); }
  3134. /** Returns true if the given unicode character can be represented in this encoding. */
  3135. static bool canRepresent (juce_wchar character) noexcept
  3136. {
  3137. return ((unsigned int) character) < (unsigned int) 0x10ffff;
  3138. }
  3139. /** Returns true if this data contains a valid string in this encoding. */
  3140. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  3141. {
  3142. maxBytesToRead /= sizeof (CharType);
  3143. while (--maxBytesToRead >= 0 && *dataToTest != 0)
  3144. if (! canRepresent (*dataToTest++))
  3145. return false;
  3146. return true;
  3147. }
  3148. /** Atomically swaps this pointer for a new value, returning the previous value. */
  3149. CharPointer_UTF32 atomicSwap (const CharPointer_UTF32& newValue)
  3150. {
  3151. return CharPointer_UTF32 (reinterpret_cast <Atomic<CharType*>&> (data).exchange (newValue.data));
  3152. }
  3153. private:
  3154. CharType* data;
  3155. };
  3156. #endif // __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  3157. /*** End of inlined file: juce_CharPointer_UTF32.h ***/
  3158. /*** Start of inlined file: juce_CharPointer_ASCII.h ***/
  3159. #ifndef __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  3160. #define __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  3161. /**
  3162. Wraps a pointer to a null-terminated ASCII character string, and provides
  3163. various methods to operate on the data.
  3164. A valid ASCII string is assumed to not contain any characters above 127.
  3165. @see CharPointer_UTF8, CharPointer_UTF16, CharPointer_UTF32
  3166. */
  3167. class CharPointer_ASCII
  3168. {
  3169. public:
  3170. typedef char CharType;
  3171. inline explicit CharPointer_ASCII (const CharType* const rawPointer) noexcept
  3172. : data (const_cast <CharType*> (rawPointer))
  3173. {
  3174. }
  3175. inline CharPointer_ASCII (const CharPointer_ASCII& other) noexcept
  3176. : data (other.data)
  3177. {
  3178. }
  3179. inline CharPointer_ASCII& operator= (const CharPointer_ASCII& other) noexcept
  3180. {
  3181. data = other.data;
  3182. return *this;
  3183. }
  3184. inline CharPointer_ASCII& operator= (const CharType* text) noexcept
  3185. {
  3186. data = const_cast <CharType*> (text);
  3187. return *this;
  3188. }
  3189. /** This is a pointer comparison, it doesn't compare the actual text. */
  3190. inline bool operator== (const CharPointer_ASCII& other) const noexcept { return data == other.data; }
  3191. inline bool operator!= (const CharPointer_ASCII& other) const noexcept { return data != other.data; }
  3192. inline bool operator<= (const CharPointer_ASCII& other) const noexcept { return data <= other.data; }
  3193. inline bool operator< (const CharPointer_ASCII& other) const noexcept { return data < other.data; }
  3194. inline bool operator>= (const CharPointer_ASCII& other) const noexcept { return data >= other.data; }
  3195. inline bool operator> (const CharPointer_ASCII& other) const noexcept { return data > other.data; }
  3196. /** Returns the address that this pointer is pointing to. */
  3197. inline CharType* getAddress() const noexcept { return data; }
  3198. /** Returns the address that this pointer is pointing to. */
  3199. inline operator const CharType*() const noexcept { return data; }
  3200. /** Returns true if this pointer is pointing to a null character. */
  3201. inline bool isEmpty() const noexcept { return *data == 0; }
  3202. /** Returns the unicode character that this pointer is pointing to. */
  3203. inline juce_wchar operator*() const noexcept { return *data; }
  3204. /** Moves this pointer along to the next character in the string. */
  3205. inline CharPointer_ASCII& operator++() noexcept
  3206. {
  3207. ++data;
  3208. return *this;
  3209. }
  3210. /** Moves this pointer to the previous character in the string. */
  3211. inline CharPointer_ASCII& operator--() noexcept
  3212. {
  3213. --data;
  3214. return *this;
  3215. }
  3216. /** Returns the character that this pointer is currently pointing to, and then
  3217. advances the pointer to point to the next character. */
  3218. inline juce_wchar getAndAdvance() noexcept { return *data++; }
  3219. /** Moves this pointer along to the next character in the string. */
  3220. CharPointer_ASCII operator++ (int) noexcept
  3221. {
  3222. CharPointer_ASCII temp (*this);
  3223. ++data;
  3224. return temp;
  3225. }
  3226. /** Moves this pointer forwards by the specified number of characters. */
  3227. inline void operator+= (const int numToSkip) noexcept
  3228. {
  3229. data += numToSkip;
  3230. }
  3231. inline void operator-= (const int numToSkip) noexcept
  3232. {
  3233. data -= numToSkip;
  3234. }
  3235. /** Returns the character at a given character index from the start of the string. */
  3236. inline juce_wchar operator[] (const int characterIndex) const noexcept
  3237. {
  3238. return (juce_wchar) (unsigned char) data [characterIndex];
  3239. }
  3240. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  3241. CharPointer_ASCII operator+ (const int numToSkip) const noexcept
  3242. {
  3243. return CharPointer_ASCII (data + numToSkip);
  3244. }
  3245. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  3246. CharPointer_ASCII operator- (const int numToSkip) const noexcept
  3247. {
  3248. return CharPointer_ASCII (data - numToSkip);
  3249. }
  3250. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  3251. inline void write (const juce_wchar charToWrite) noexcept
  3252. {
  3253. *data++ = (char) charToWrite;
  3254. }
  3255. inline void replaceChar (const juce_wchar newChar) noexcept
  3256. {
  3257. *data = (char) newChar;
  3258. }
  3259. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  3260. inline void writeNull() const noexcept
  3261. {
  3262. *data = 0;
  3263. }
  3264. /** Returns the number of characters in this string. */
  3265. size_t length() const noexcept
  3266. {
  3267. return (size_t) strlen (data);
  3268. }
  3269. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  3270. size_t lengthUpTo (const size_t maxCharsToCount) const noexcept
  3271. {
  3272. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  3273. }
  3274. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  3275. size_t lengthUpTo (const CharPointer_ASCII& end) const noexcept
  3276. {
  3277. return CharacterFunctions::lengthUpTo (*this, end);
  3278. }
  3279. /** Returns the number of bytes that are used to represent this string.
  3280. This includes the terminating null character.
  3281. */
  3282. size_t sizeInBytes() const noexcept
  3283. {
  3284. return length() + 1;
  3285. }
  3286. /** Returns the number of bytes that would be needed to represent the given
  3287. unicode character in this encoding format.
  3288. */
  3289. static inline size_t getBytesRequiredFor (const juce_wchar) noexcept
  3290. {
  3291. return 1;
  3292. }
  3293. /** Returns the number of bytes that would be needed to represent the given
  3294. string in this encoding format.
  3295. The value returned does NOT include the terminating null character.
  3296. */
  3297. template <class CharPointer>
  3298. static size_t getBytesRequiredFor (const CharPointer& text) noexcept
  3299. {
  3300. return text.length();
  3301. }
  3302. /** Returns a pointer to the null character that terminates this string. */
  3303. CharPointer_ASCII findTerminatingNull() const noexcept
  3304. {
  3305. return CharPointer_ASCII (data + length());
  3306. }
  3307. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3308. template <typename CharPointer>
  3309. void writeAll (const CharPointer& src) noexcept
  3310. {
  3311. CharacterFunctions::copyAll (*this, src);
  3312. }
  3313. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3314. void writeAll (const CharPointer_ASCII& src) noexcept
  3315. {
  3316. strcpy (data, src.data);
  3317. }
  3318. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3319. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  3320. to the destination buffer before stopping.
  3321. */
  3322. template <typename CharPointer>
  3323. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) noexcept
  3324. {
  3325. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  3326. }
  3327. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3328. The maxChars parameter specifies the maximum number of characters that can be
  3329. written to the destination buffer before stopping (including the terminating null).
  3330. */
  3331. template <typename CharPointer>
  3332. void writeWithCharLimit (const CharPointer& src, const int maxChars) noexcept
  3333. {
  3334. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  3335. }
  3336. /** Compares this string with another one. */
  3337. template <typename CharPointer>
  3338. int compare (const CharPointer& other) const noexcept
  3339. {
  3340. return CharacterFunctions::compare (*this, other);
  3341. }
  3342. /** Compares this string with another one. */
  3343. int compare (const CharPointer_ASCII& other) const noexcept
  3344. {
  3345. return strcmp (data, other.data);
  3346. }
  3347. /** Compares this string with another one, up to a specified number of characters. */
  3348. template <typename CharPointer>
  3349. int compareUpTo (const CharPointer& other, const int maxChars) const noexcept
  3350. {
  3351. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  3352. }
  3353. /** Compares this string with another one, up to a specified number of characters. */
  3354. int compareUpTo (const CharPointer_ASCII& other, const int maxChars) const noexcept
  3355. {
  3356. return strncmp (data, other.data, (size_t) maxChars);
  3357. }
  3358. /** Compares this string with another one. */
  3359. template <typename CharPointer>
  3360. int compareIgnoreCase (const CharPointer& other) const
  3361. {
  3362. return CharacterFunctions::compareIgnoreCase (*this, other);
  3363. }
  3364. int compareIgnoreCase (const CharPointer_ASCII& other) const
  3365. {
  3366. #if JUCE_WINDOWS
  3367. return stricmp (data, other.data);
  3368. #else
  3369. return strcasecmp (data, other.data);
  3370. #endif
  3371. }
  3372. /** Compares this string with another one, up to a specified number of characters. */
  3373. template <typename CharPointer>
  3374. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const noexcept
  3375. {
  3376. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  3377. }
  3378. /** Returns the character index of a substring, or -1 if it isn't found. */
  3379. template <typename CharPointer>
  3380. int indexOf (const CharPointer& stringToFind) const noexcept
  3381. {
  3382. return CharacterFunctions::indexOf (*this, stringToFind);
  3383. }
  3384. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3385. int indexOf (const juce_wchar charToFind) const noexcept
  3386. {
  3387. int i = 0;
  3388. while (data[i] != 0)
  3389. {
  3390. if (data[i] == (char) charToFind)
  3391. return i;
  3392. ++i;
  3393. }
  3394. return -1;
  3395. }
  3396. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3397. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const noexcept
  3398. {
  3399. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  3400. : CharacterFunctions::indexOfChar (*this, charToFind);
  3401. }
  3402. /** Returns true if the first character of this string is whitespace. */
  3403. bool isWhitespace() const { return CharacterFunctions::isWhitespace (*data) != 0; }
  3404. /** Returns true if the first character of this string is a digit. */
  3405. bool isDigit() const { return CharacterFunctions::isDigit (*data) != 0; }
  3406. /** Returns true if the first character of this string is a letter. */
  3407. bool isLetter() const { return CharacterFunctions::isLetter (*data) != 0; }
  3408. /** Returns true if the first character of this string is a letter or digit. */
  3409. bool isLetterOrDigit() const { return CharacterFunctions::isLetterOrDigit (*data) != 0; }
  3410. /** Returns true if the first character of this string is upper-case. */
  3411. bool isUpperCase() const { return CharacterFunctions::isUpperCase (*data) != 0; }
  3412. /** Returns true if the first character of this string is lower-case. */
  3413. bool isLowerCase() const { return CharacterFunctions::isLowerCase (*data) != 0; }
  3414. /** Returns an upper-case version of the first character of this string. */
  3415. juce_wchar toUpperCase() const noexcept { return CharacterFunctions::toUpperCase (*data); }
  3416. /** Returns a lower-case version of the first character of this string. */
  3417. juce_wchar toLowerCase() const noexcept { return CharacterFunctions::toLowerCase (*data); }
  3418. /** Parses this string as a 32-bit integer. */
  3419. int getIntValue32() const noexcept { return atoi (data); }
  3420. /** Parses this string as a 64-bit integer. */
  3421. int64 getIntValue64() const noexcept
  3422. {
  3423. #if JUCE_LINUX || JUCE_ANDROID
  3424. return atoll (data);
  3425. #elif JUCE_WINDOWS
  3426. return _atoi64 (data);
  3427. #else
  3428. return CharacterFunctions::getIntValue <int64, CharPointer_ASCII> (*this);
  3429. #endif
  3430. }
  3431. /** Parses this string as a floating point double. */
  3432. double getDoubleValue() const noexcept { return CharacterFunctions::getDoubleValue (*this); }
  3433. /** Returns the first non-whitespace character in the string. */
  3434. CharPointer_ASCII findEndOfWhitespace() const noexcept { return CharacterFunctions::findEndOfWhitespace (*this); }
  3435. /** Returns true if the given unicode character can be represented in this encoding. */
  3436. static bool canRepresent (juce_wchar character) noexcept
  3437. {
  3438. return ((unsigned int) character) < (unsigned int) 128;
  3439. }
  3440. /** Returns true if this data contains a valid string in this encoding. */
  3441. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  3442. {
  3443. while (--maxBytesToRead >= 0)
  3444. {
  3445. if (((signed char) *dataToTest) <= 0)
  3446. return *dataToTest == 0;
  3447. ++dataToTest;
  3448. }
  3449. return true;
  3450. }
  3451. private:
  3452. CharType* data;
  3453. };
  3454. #endif // __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  3455. /*** End of inlined file: juce_CharPointer_ASCII.h ***/
  3456. #if JUCE_MSVC
  3457. #pragma warning (pop)
  3458. #endif
  3459. class OutputStream;
  3460. /**
  3461. The JUCE String class!
  3462. Using a reference-counted internal representation, these strings are fast
  3463. and efficient, and there are methods to do just about any operation you'll ever
  3464. dream of.
  3465. @see StringArray, StringPairArray
  3466. */
  3467. class JUCE_API String
  3468. {
  3469. public:
  3470. /** Creates an empty string.
  3471. @see empty
  3472. */
  3473. String() noexcept;
  3474. /** Creates a copy of another string. */
  3475. String (const String& other) noexcept;
  3476. /** Creates a string from a zero-terminated ascii text string.
  3477. The string passed-in must not contain any characters with a value above 127, because
  3478. these can't be converted to unicode without knowing the original encoding that was
  3479. used to create the string. If you attempt to pass-in values above 127, you'll get an
  3480. assertion.
  3481. To create strings with extended characters from UTF-8, you should explicitly call
  3482. String (CharPointer_UTF8 ("my utf8 string..")). It's *highly* recommended that you
  3483. use UTF-8 with escape characters in your source code to represent extended characters,
  3484. because there's no other way to represent unicode strings in a way that isn't dependent
  3485. on the compiler, source code editor and platform.
  3486. */
  3487. String (const char* text);
  3488. /** Creates a string from a string of 8-bit ascii characters.
  3489. The string passed-in must not contain any characters with a value above 127, because
  3490. these can't be converted to unicode without knowing the original encoding that was
  3491. used to create the string. If you attempt to pass-in values above 127, you'll get an
  3492. assertion.
  3493. To create strings with extended characters from UTF-8, you should explicitly call
  3494. String (CharPointer_UTF8 ("my utf8 string..")). It's *highly* recommended that you
  3495. use UTF-8 with escape characters in your source code to represent extended characters,
  3496. because there's no other way to represent unicode strings in a way that isn't dependent
  3497. on the compiler, source code editor and platform.
  3498. This will use up the the first maxChars characters of the string (or less if the string
  3499. is actually shorter).
  3500. */
  3501. String (const char* text, size_t maxChars);
  3502. /** Creates a string from a whcar_t character string.
  3503. Depending on the platform, this may be treated as either UTF-32 or UTF-16.
  3504. */
  3505. String (const wchar_t* text);
  3506. /** Creates a string from a whcar_t character string.
  3507. Depending on the platform, this may be treated as either UTF-32 or UTF-16.
  3508. */
  3509. String (const wchar_t* text, size_t maxChars);
  3510. /** Creates a string from a UTF-8 character string */
  3511. String (const CharPointer_UTF8& text);
  3512. /** Creates a string from a UTF-8 character string */
  3513. String (const CharPointer_UTF8& text, size_t maxChars);
  3514. /** Creates a string from a UTF-8 character string */
  3515. String (const CharPointer_UTF8& start, const CharPointer_UTF8& end);
  3516. /** Creates a string from a UTF-16 character string */
  3517. String (const CharPointer_UTF16& text);
  3518. /** Creates a string from a UTF-16 character string */
  3519. String (const CharPointer_UTF16& text, size_t maxChars);
  3520. /** Creates a string from a UTF-16 character string */
  3521. String (const CharPointer_UTF16& start, const CharPointer_UTF16& end);
  3522. /** Creates a string from a UTF-32 character string */
  3523. String (const CharPointer_UTF32& text);
  3524. /** Creates a string from a UTF-32 character string */
  3525. String (const CharPointer_UTF32& text, size_t maxChars);
  3526. /** Creates a string from a UTF-32 character string */
  3527. String (const CharPointer_UTF32& start, const CharPointer_UTF32& end);
  3528. /** Creates a string from an ASCII character string */
  3529. String (const CharPointer_ASCII& text);
  3530. /** Creates a string from a single character. */
  3531. static String charToString (juce_wchar character);
  3532. /** Destructor. */
  3533. ~String() noexcept;
  3534. /** This is an empty string that can be used whenever one is needed.
  3535. It's better to use this than String() because it explains what's going on
  3536. and is more efficient.
  3537. */
  3538. static const String empty;
  3539. /** This is the character encoding type used internally to store the string.
  3540. By setting the value of JUCE_STRING_UTF_TYPE to 8, 16, or 32, you can change the
  3541. internal storage format of the String class. UTF-8 uses the least space (if your strings
  3542. contain few extended characters), but call operator[] involves iterating the string to find
  3543. the required index. UTF-32 provides instant random access to its characters, but uses 4 bytes
  3544. per character to store them. UTF-16 uses more space than UTF-8 and is also slow to index,
  3545. but is the native wchar_t format used in Windows.
  3546. It doesn't matter too much which format you pick, because the toUTF8(), toUTF16() and
  3547. toUTF32() methods let you access the string's content in any of the other formats.
  3548. */
  3549. #if (JUCE_STRING_UTF_TYPE == 32)
  3550. typedef CharPointer_UTF32 CharPointerType;
  3551. #elif (JUCE_STRING_UTF_TYPE == 16)
  3552. typedef CharPointer_UTF16 CharPointerType;
  3553. #elif (JUCE_STRING_UTF_TYPE == 8)
  3554. typedef CharPointer_UTF8 CharPointerType;
  3555. #else
  3556. #error "You must set the value of JUCE_STRING_UTF_TYPE to be either 8, 16, or 32!"
  3557. #endif
  3558. /** Generates a probably-unique 32-bit hashcode from this string. */
  3559. int hashCode() const noexcept;
  3560. /** Generates a probably-unique 64-bit hashcode from this string. */
  3561. int64 hashCode64() const noexcept;
  3562. /** Returns the number of characters in the string. */
  3563. int length() const noexcept;
  3564. // Assignment and concatenation operators..
  3565. /** Replaces this string's contents with another string. */
  3566. String& operator= (const String& other) noexcept;
  3567. /** Appends another string at the end of this one. */
  3568. String& operator+= (const String& stringToAppend);
  3569. /** Appends another string at the end of this one. */
  3570. String& operator+= (const char* textToAppend);
  3571. /** Appends another string at the end of this one. */
  3572. String& operator+= (const wchar_t* textToAppend);
  3573. /** Appends a decimal number at the end of this string. */
  3574. String& operator+= (int numberToAppend);
  3575. /** Appends a character at the end of this string. */
  3576. String& operator+= (char characterToAppend);
  3577. /** Appends a character at the end of this string. */
  3578. String& operator+= (wchar_t characterToAppend);
  3579. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  3580. /** Appends a character at the end of this string. */
  3581. String& operator+= (juce_wchar characterToAppend);
  3582. #endif
  3583. /** Appends a string to the end of this one.
  3584. @param textToAppend the string to add
  3585. @param maxCharsToTake the maximum number of characters to take from the string passed in
  3586. */
  3587. void append (const String& textToAppend, size_t maxCharsToTake);
  3588. /** Appends a string to the end of this one.
  3589. @param textToAppend the string to add
  3590. @param maxCharsToTake the maximum number of characters to take from the string passed in
  3591. */
  3592. template <class CharPointer>
  3593. void appendCharPointer (const CharPointer& textToAppend, size_t maxCharsToTake)
  3594. {
  3595. if (textToAppend.getAddress() != nullptr)
  3596. {
  3597. size_t extraBytesNeeded = 0;
  3598. size_t numChars = 0;
  3599. for (CharPointer t (textToAppend); numChars < maxCharsToTake && ! t.isEmpty();)
  3600. {
  3601. extraBytesNeeded += CharPointerType::getBytesRequiredFor (t.getAndAdvance());
  3602. ++numChars;
  3603. }
  3604. if (numChars > 0)
  3605. {
  3606. const size_t byteOffsetOfNull = getByteOffsetOfEnd();
  3607. preallocateBytes (byteOffsetOfNull + extraBytesNeeded);
  3608. CharPointerType (addBytesToPointer (text.getAddress(), (int) byteOffsetOfNull)).writeWithCharLimit (textToAppend, (int) (numChars + 1));
  3609. }
  3610. }
  3611. }
  3612. /** Appends a string to the end of this one. */
  3613. template <class CharPointer>
  3614. void appendCharPointer (const CharPointer& textToAppend)
  3615. {
  3616. if (textToAppend.getAddress() != nullptr)
  3617. {
  3618. size_t extraBytesNeeded = 0;
  3619. for (CharPointer t (textToAppend); ! t.isEmpty();)
  3620. extraBytesNeeded += CharPointerType::getBytesRequiredFor (t.getAndAdvance());
  3621. if (extraBytesNeeded > 0)
  3622. {
  3623. const size_t byteOffsetOfNull = getByteOffsetOfEnd();
  3624. preallocateBytes (byteOffsetOfNull + extraBytesNeeded);
  3625. CharPointerType (addBytesToPointer (text.getAddress(), (int) byteOffsetOfNull)).writeAll (textToAppend);
  3626. }
  3627. }
  3628. }
  3629. // Comparison methods..
  3630. /** Returns true if the string contains no characters.
  3631. Note that there's also an isNotEmpty() method to help write readable code.
  3632. @see containsNonWhitespaceChars()
  3633. */
  3634. inline bool isEmpty() const noexcept { return text[0] == 0; }
  3635. /** Returns true if the string contains at least one character.
  3636. Note that there's also an isEmpty() method to help write readable code.
  3637. @see containsNonWhitespaceChars()
  3638. */
  3639. inline bool isNotEmpty() const noexcept { return text[0] != 0; }
  3640. /** Case-insensitive comparison with another string. */
  3641. bool equalsIgnoreCase (const String& other) const noexcept;
  3642. /** Case-insensitive comparison with another string. */
  3643. bool equalsIgnoreCase (const wchar_t* other) const noexcept;
  3644. /** Case-insensitive comparison with another string. */
  3645. bool equalsIgnoreCase (const char* other) const noexcept;
  3646. /** Case-sensitive comparison with another string.
  3647. @returns 0 if the two strings are identical; negative if this string comes before
  3648. the other one alphabetically, or positive if it comes after it.
  3649. */
  3650. int compare (const String& other) const noexcept;
  3651. /** Case-sensitive comparison with another string.
  3652. @returns 0 if the two strings are identical; negative if this string comes before
  3653. the other one alphabetically, or positive if it comes after it.
  3654. */
  3655. int compare (const char* other) const noexcept;
  3656. /** Case-sensitive comparison with another string.
  3657. @returns 0 if the two strings are identical; negative if this string comes before
  3658. the other one alphabetically, or positive if it comes after it.
  3659. */
  3660. int compare (const wchar_t* other) const noexcept;
  3661. /** Case-insensitive comparison with another string.
  3662. @returns 0 if the two strings are identical; negative if this string comes before
  3663. the other one alphabetically, or positive if it comes after it.
  3664. */
  3665. int compareIgnoreCase (const String& other) const noexcept;
  3666. /** Lexicographic comparison with another string.
  3667. The comparison used here is case-insensitive and ignores leading non-alphanumeric
  3668. characters, making it good for sorting human-readable strings.
  3669. @returns 0 if the two strings are identical; negative if this string comes before
  3670. the other one alphabetically, or positive if it comes after it.
  3671. */
  3672. int compareLexicographically (const String& other) const noexcept;
  3673. /** Tests whether the string begins with another string.
  3674. If the parameter is an empty string, this will always return true.
  3675. Uses a case-sensitive comparison.
  3676. */
  3677. bool startsWith (const String& text) const noexcept;
  3678. /** Tests whether the string begins with a particular character.
  3679. If the character is 0, this will always return false.
  3680. Uses a case-sensitive comparison.
  3681. */
  3682. bool startsWithChar (juce_wchar character) const noexcept;
  3683. /** Tests whether the string begins with another string.
  3684. If the parameter is an empty string, this will always return true.
  3685. Uses a case-insensitive comparison.
  3686. */
  3687. bool startsWithIgnoreCase (const String& text) const noexcept;
  3688. /** Tests whether the string ends with another string.
  3689. If the parameter is an empty string, this will always return true.
  3690. Uses a case-sensitive comparison.
  3691. */
  3692. bool endsWith (const String& text) const noexcept;
  3693. /** Tests whether the string ends with a particular character.
  3694. If the character is 0, this will always return false.
  3695. Uses a case-sensitive comparison.
  3696. */
  3697. bool endsWithChar (juce_wchar character) const noexcept;
  3698. /** Tests whether the string ends with another string.
  3699. If the parameter is an empty string, this will always return true.
  3700. Uses a case-insensitive comparison.
  3701. */
  3702. bool endsWithIgnoreCase (const String& text) const noexcept;
  3703. /** Tests whether the string contains another substring.
  3704. If the parameter is an empty string, this will always return true.
  3705. Uses a case-sensitive comparison.
  3706. */
  3707. bool contains (const String& text) const noexcept;
  3708. /** Tests whether the string contains a particular character.
  3709. Uses a case-sensitive comparison.
  3710. */
  3711. bool containsChar (juce_wchar character) const noexcept;
  3712. /** Tests whether the string contains another substring.
  3713. Uses a case-insensitive comparison.
  3714. */
  3715. bool containsIgnoreCase (const String& text) const noexcept;
  3716. /** Tests whether the string contains another substring as a distict word.
  3717. @returns true if the string contains this word, surrounded by
  3718. non-alphanumeric characters
  3719. @see indexOfWholeWord, containsWholeWordIgnoreCase
  3720. */
  3721. bool containsWholeWord (const String& wordToLookFor) const noexcept;
  3722. /** Tests whether the string contains another substring as a distict word.
  3723. @returns true if the string contains this word, surrounded by
  3724. non-alphanumeric characters
  3725. @see indexOfWholeWordIgnoreCase, containsWholeWord
  3726. */
  3727. bool containsWholeWordIgnoreCase (const String& wordToLookFor) const noexcept;
  3728. /** Finds an instance of another substring if it exists as a distict word.
  3729. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  3730. then this will return the index of the start of the substring. If it isn't
  3731. found, then it will return -1
  3732. @see indexOfWholeWordIgnoreCase, containsWholeWord
  3733. */
  3734. int indexOfWholeWord (const String& wordToLookFor) const noexcept;
  3735. /** Finds an instance of another substring if it exists as a distict word.
  3736. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  3737. then this will return the index of the start of the substring. If it isn't
  3738. found, then it will return -1
  3739. @see indexOfWholeWord, containsWholeWordIgnoreCase
  3740. */
  3741. int indexOfWholeWordIgnoreCase (const String& wordToLookFor) const noexcept;
  3742. /** Looks for any of a set of characters in the string.
  3743. Uses a case-sensitive comparison.
  3744. @returns true if the string contains any of the characters from
  3745. the string that is passed in.
  3746. */
  3747. bool containsAnyOf (const String& charactersItMightContain) const noexcept;
  3748. /** Looks for a set of characters in the string.
  3749. Uses a case-sensitive comparison.
  3750. @returns Returns false if any of the characters in this string do not occur in
  3751. the parameter string. If this string is empty, the return value will
  3752. always be true.
  3753. */
  3754. bool containsOnly (const String& charactersItMightContain) const noexcept;
  3755. /** Returns true if this string contains any non-whitespace characters.
  3756. This will return false if the string contains only whitespace characters, or
  3757. if it's empty.
  3758. It is equivalent to calling "myString.trim().isNotEmpty()".
  3759. */
  3760. bool containsNonWhitespaceChars() const noexcept;
  3761. /** Returns true if the string matches this simple wildcard expression.
  3762. So for example String ("abcdef").matchesWildcard ("*DEF", true) would return true.
  3763. This isn't a full-blown regex though! The only wildcard characters supported
  3764. are "*" and "?". It's mainly intended for filename pattern matching.
  3765. */
  3766. bool matchesWildcard (const String& wildcard, bool ignoreCase) const noexcept;
  3767. // Substring location methods..
  3768. /** Searches for a character inside this string.
  3769. Uses a case-sensitive comparison.
  3770. @returns the index of the first occurrence of the character in this
  3771. string, or -1 if it's not found.
  3772. */
  3773. int indexOfChar (juce_wchar characterToLookFor) const noexcept;
  3774. /** Searches for a character inside this string.
  3775. Uses a case-sensitive comparison.
  3776. @param startIndex the index from which the search should proceed
  3777. @param characterToLookFor the character to look for
  3778. @returns the index of the first occurrence of the character in this
  3779. string, or -1 if it's not found.
  3780. */
  3781. int indexOfChar (int startIndex, juce_wchar characterToLookFor) const noexcept;
  3782. /** Returns the index of the first character that matches one of the characters
  3783. passed-in to this method.
  3784. This scans the string, beginning from the startIndex supplied, and if it finds
  3785. a character that appears in the string charactersToLookFor, it returns its index.
  3786. If none of these characters are found, it returns -1.
  3787. If ignoreCase is true, the comparison will be case-insensitive.
  3788. @see indexOfChar, lastIndexOfAnyOf
  3789. */
  3790. int indexOfAnyOf (const String& charactersToLookFor,
  3791. int startIndex = 0,
  3792. bool ignoreCase = false) const noexcept;
  3793. /** Searches for a substring within this string.
  3794. Uses a case-sensitive comparison.
  3795. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3796. If textToLookFor is an empty string, this will always return 0.
  3797. */
  3798. int indexOf (const String& textToLookFor) const noexcept;
  3799. /** Searches for a substring within this string.
  3800. Uses a case-sensitive comparison.
  3801. @param startIndex the index from which the search should proceed
  3802. @param textToLookFor the string to search for
  3803. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3804. If textToLookFor is an empty string, this will always return -1.
  3805. */
  3806. int indexOf (int startIndex, const String& textToLookFor) const noexcept;
  3807. /** Searches for a substring within this string.
  3808. Uses a case-insensitive comparison.
  3809. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3810. If textToLookFor is an empty string, this will always return 0.
  3811. */
  3812. int indexOfIgnoreCase (const String& textToLookFor) const noexcept;
  3813. /** Searches for a substring within this string.
  3814. Uses a case-insensitive comparison.
  3815. @param startIndex the index from which the search should proceed
  3816. @param textToLookFor the string to search for
  3817. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3818. If textToLookFor is an empty string, this will always return -1.
  3819. */
  3820. int indexOfIgnoreCase (int startIndex, const String& textToLookFor) const noexcept;
  3821. /** Searches for a character inside this string (working backwards from the end of the string).
  3822. Uses a case-sensitive comparison.
  3823. @returns the index of the last occurrence of the character in this string, or -1 if it's not found.
  3824. */
  3825. int lastIndexOfChar (juce_wchar character) const noexcept;
  3826. /** Searches for a substring inside this string (working backwards from the end of the string).
  3827. Uses a case-sensitive comparison.
  3828. @returns the index of the start of the last occurrence of the substring within this string,
  3829. or -1 if it's not found. If textToLookFor is an empty string, this will always return -1.
  3830. */
  3831. int lastIndexOf (const String& textToLookFor) const noexcept;
  3832. /** Searches for a substring inside this string (working backwards from the end of the string).
  3833. Uses a case-insensitive comparison.
  3834. @returns the index of the start of the last occurrence of the substring within this string, or -1
  3835. if it's not found. If textToLookFor is an empty string, this will always return -1.
  3836. */
  3837. int lastIndexOfIgnoreCase (const String& textToLookFor) const noexcept;
  3838. /** Returns the index of the last character in this string that matches one of the
  3839. characters passed-in to this method.
  3840. This scans the string backwards, starting from its end, and if it finds
  3841. a character that appears in the string charactersToLookFor, it returns its index.
  3842. If none of these characters are found, it returns -1.
  3843. If ignoreCase is true, the comparison will be case-insensitive.
  3844. @see lastIndexOf, indexOfAnyOf
  3845. */
  3846. int lastIndexOfAnyOf (const String& charactersToLookFor,
  3847. bool ignoreCase = false) const noexcept;
  3848. // Substring extraction and manipulation methods..
  3849. /** Returns the character at this index in the string.
  3850. In a release build, no checks are made to see if the index is within a valid range, so be
  3851. careful! In a debug build, the index is checked and an assertion fires if it's out-of-range.
  3852. Also beware that depending on the encoding format that the string is using internally, this
  3853. method may execute in either O(1) or O(n) time, so be careful when using it in your algorithms.
  3854. If you're scanning through a string to inspect its characters, you should never use this operator
  3855. for random access, it's far more efficient to call getCharPointer() to return a pointer, and
  3856. then to use that to iterate the string.
  3857. @see getCharPointer
  3858. */
  3859. const juce_wchar operator[] (int index) const noexcept;
  3860. /** Returns the final character of the string.
  3861. If the string is empty this will return 0.
  3862. */
  3863. juce_wchar getLastCharacter() const noexcept;
  3864. /** Returns a subsection of the string.
  3865. If the range specified is beyond the limits of the string, as much as
  3866. possible is returned.
  3867. @param startIndex the index of the start of the substring needed
  3868. @param endIndex all characters from startIndex up to (but not including)
  3869. this index are returned
  3870. @see fromFirstOccurrenceOf, dropLastCharacters, getLastCharacters, upToFirstOccurrenceOf
  3871. */
  3872. String substring (int startIndex, int endIndex) const;
  3873. /** Returns a section of the string, starting from a given position.
  3874. @param startIndex the first character to include. If this is beyond the end
  3875. of the string, an empty string is returned. If it is zero or
  3876. less, the whole string is returned.
  3877. @returns the substring from startIndex up to the end of the string
  3878. @see dropLastCharacters, getLastCharacters, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf
  3879. */
  3880. String substring (int startIndex) const;
  3881. /** Returns a version of this string with a number of characters removed
  3882. from the end.
  3883. @param numberToDrop the number of characters to drop from the end of the
  3884. string. If this is greater than the length of the string,
  3885. an empty string will be returned. If zero or less, the
  3886. original string will be returned.
  3887. @see substring, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf, getLastCharacter
  3888. */
  3889. String dropLastCharacters (int numberToDrop) const;
  3890. /** Returns a number of characters from the end of the string.
  3891. This returns the last numCharacters characters from the end of the string. If the
  3892. string is shorter than numCharacters, the whole string is returned.
  3893. @see substring, dropLastCharacters, getLastCharacter
  3894. */
  3895. String getLastCharacters (int numCharacters) const;
  3896. /** Returns a section of the string starting from a given substring.
  3897. This will search for the first occurrence of the given substring, and
  3898. return the section of the string starting from the point where this is
  3899. found (optionally not including the substring itself).
  3900. e.g. for the string "123456", fromFirstOccurrenceOf ("34", true) would return "3456", and
  3901. fromFirstOccurrenceOf ("34", false) would return "56".
  3902. If the substring isn't found, the method will return an empty string.
  3903. If ignoreCase is true, the comparison will be case-insensitive.
  3904. @see upToFirstOccurrenceOf, fromLastOccurrenceOf
  3905. */
  3906. String fromFirstOccurrenceOf (const String& substringToStartFrom,
  3907. bool includeSubStringInResult,
  3908. bool ignoreCase) const;
  3909. /** Returns a section of the string starting from the last occurrence of a given substring.
  3910. Similar to fromFirstOccurrenceOf(), but using the last occurrence of the substring, and
  3911. unlike fromFirstOccurrenceOf(), if the substring isn't found, this method will
  3912. return the whole of the original string.
  3913. @see fromFirstOccurrenceOf, upToLastOccurrenceOf
  3914. */
  3915. String fromLastOccurrenceOf (const String& substringToFind,
  3916. bool includeSubStringInResult,
  3917. bool ignoreCase) const;
  3918. /** Returns the start of this string, up to the first occurrence of a substring.
  3919. This will search for the first occurrence of a given substring, and then
  3920. return a copy of the string, up to the position of this substring,
  3921. optionally including or excluding the substring itself in the result.
  3922. e.g. for the string "123456", upTo ("34", false) would return "12", and
  3923. upTo ("34", true) would return "1234".
  3924. If the substring isn't found, this will return the whole of the original string.
  3925. @see upToLastOccurrenceOf, fromFirstOccurrenceOf
  3926. */
  3927. String upToFirstOccurrenceOf (const String& substringToEndWith,
  3928. bool includeSubStringInResult,
  3929. bool ignoreCase) const;
  3930. /** Returns the start of this string, up to the last occurrence of a substring.
  3931. Similar to upToFirstOccurrenceOf(), but this finds the last occurrence rather than the first.
  3932. If the substring isn't found, this will return the whole of the original string.
  3933. @see upToFirstOccurrenceOf, fromFirstOccurrenceOf
  3934. */
  3935. String upToLastOccurrenceOf (const String& substringToFind,
  3936. bool includeSubStringInResult,
  3937. bool ignoreCase) const;
  3938. /** Returns a copy of this string with any whitespace characters removed from the start and end. */
  3939. String trim() const;
  3940. /** Returns a copy of this string with any whitespace characters removed from the start. */
  3941. String trimStart() const;
  3942. /** Returns a copy of this string with any whitespace characters removed from the end. */
  3943. String trimEnd() const;
  3944. /** Returns a copy of this string, having removed a specified set of characters from its start.
  3945. Characters are removed from the start of the string until it finds one that is not in the
  3946. specified set, and then it stops.
  3947. @param charactersToTrim the set of characters to remove.
  3948. @see trim, trimStart, trimCharactersAtEnd
  3949. */
  3950. String trimCharactersAtStart (const String& charactersToTrim) const;
  3951. /** Returns a copy of this string, having removed a specified set of characters from its end.
  3952. Characters are removed from the end of the string until it finds one that is not in the
  3953. specified set, and then it stops.
  3954. @param charactersToTrim the set of characters to remove.
  3955. @see trim, trimEnd, trimCharactersAtStart
  3956. */
  3957. String trimCharactersAtEnd (const String& charactersToTrim) const;
  3958. /** Returns an upper-case version of this string. */
  3959. String toUpperCase() const;
  3960. /** Returns an lower-case version of this string. */
  3961. String toLowerCase() const;
  3962. /** Replaces a sub-section of the string with another string.
  3963. This will return a copy of this string, with a set of characters
  3964. from startIndex to startIndex + numCharsToReplace removed, and with
  3965. a new string inserted in their place.
  3966. Note that this is a const method, and won't alter the string itself.
  3967. @param startIndex the first character to remove. If this is beyond the bounds of the string,
  3968. it will be constrained to a valid range.
  3969. @param numCharactersToReplace the number of characters to remove. If zero or less, no
  3970. characters will be taken out.
  3971. @param stringToInsert the new string to insert at startIndex after the characters have been
  3972. removed.
  3973. */
  3974. String replaceSection (int startIndex,
  3975. int numCharactersToReplace,
  3976. const String& stringToInsert) const;
  3977. /** Replaces all occurrences of a substring with another string.
  3978. Returns a copy of this string, with any occurrences of stringToReplace
  3979. swapped for stringToInsertInstead.
  3980. Note that this is a const method, and won't alter the string itself.
  3981. */
  3982. String replace (const String& stringToReplace,
  3983. const String& stringToInsertInstead,
  3984. bool ignoreCase = false) const;
  3985. /** Returns a string with all occurrences of a character replaced with a different one. */
  3986. String replaceCharacter (juce_wchar characterToReplace,
  3987. juce_wchar characterToInsertInstead) const;
  3988. /** Replaces a set of characters with another set.
  3989. Returns a string in which each character from charactersToReplace has been replaced
  3990. by the character at the equivalent position in newCharacters (so the two strings
  3991. passed in must be the same length).
  3992. e.g. replaceCharacters ("abc", "def") replaces 'a' with 'd', 'b' with 'e', etc.
  3993. Note that this is a const method, and won't affect the string itself.
  3994. */
  3995. String replaceCharacters (const String& charactersToReplace,
  3996. const String& charactersToInsertInstead) const;
  3997. /** Returns a version of this string that only retains a fixed set of characters.
  3998. This will return a copy of this string, omitting any characters which are not
  3999. found in the string passed-in.
  4000. e.g. for "1122334455", retainCharacters ("432") would return "223344"
  4001. Note that this is a const method, and won't alter the string itself.
  4002. */
  4003. String retainCharacters (const String& charactersToRetain) const;
  4004. /** Returns a version of this string with a set of characters removed.
  4005. This will return a copy of this string, omitting any characters which are
  4006. found in the string passed-in.
  4007. e.g. for "1122334455", removeCharacters ("432") would return "1155"
  4008. Note that this is a const method, and won't alter the string itself.
  4009. */
  4010. String removeCharacters (const String& charactersToRemove) const;
  4011. /** Returns a section from the start of the string that only contains a certain set of characters.
  4012. This returns the leftmost section of the string, up to (and not including) the
  4013. first character that doesn't appear in the string passed in.
  4014. */
  4015. String initialSectionContainingOnly (const String& permittedCharacters) const;
  4016. /** Returns a section from the start of the string that only contains a certain set of characters.
  4017. This returns the leftmost section of the string, up to (and not including) the
  4018. first character that occurs in the string passed in. (If none of the specified
  4019. characters are found in the string, the return value will just be the original string).
  4020. */
  4021. String initialSectionNotContaining (const String& charactersToStopAt) const;
  4022. /** Checks whether the string might be in quotation marks.
  4023. @returns true if the string begins with a quote character (either a double or single quote).
  4024. It is also true if there is whitespace before the quote, but it doesn't check the end of the string.
  4025. @see unquoted, quoted
  4026. */
  4027. bool isQuotedString() const;
  4028. /** Removes quotation marks from around the string, (if there are any).
  4029. Returns a copy of this string with any quotes removed from its ends. Quotes that aren't
  4030. at the ends of the string are not affected. If there aren't any quotes, the original string
  4031. is returned.
  4032. Note that this is a const method, and won't alter the string itself.
  4033. @see isQuotedString, quoted
  4034. */
  4035. String unquoted() const;
  4036. /** Adds quotation marks around a string.
  4037. This will return a copy of the string with a quote at the start and end, (but won't
  4038. add the quote if there's already one there, so it's safe to call this on strings that
  4039. may already have quotes around them).
  4040. Note that this is a const method, and won't alter the string itself.
  4041. @param quoteCharacter the character to add at the start and end
  4042. @see isQuotedString, unquoted
  4043. */
  4044. String quoted (juce_wchar quoteCharacter = '"') const;
  4045. /** Creates a string which is a version of a string repeated and joined together.
  4046. @param stringToRepeat the string to repeat
  4047. @param numberOfTimesToRepeat how many times to repeat it
  4048. */
  4049. static String repeatedString (const String& stringToRepeat,
  4050. int numberOfTimesToRepeat);
  4051. /** Returns a copy of this string with the specified character repeatedly added to its
  4052. beginning until the total length is at least the minimum length specified.
  4053. */
  4054. String paddedLeft (juce_wchar padCharacter, int minimumLength) const;
  4055. /** Returns a copy of this string with the specified character repeatedly added to its
  4056. end until the total length is at least the minimum length specified.
  4057. */
  4058. String paddedRight (juce_wchar padCharacter, int minimumLength) const;
  4059. /** Creates a string from data in an unknown format.
  4060. This looks at some binary data and tries to guess whether it's Unicode
  4061. or 8-bit characters, then returns a string that represents it correctly.
  4062. Should be able to handle Unicode endianness correctly, by looking at
  4063. the first two bytes.
  4064. */
  4065. static String createStringFromData (const void* data, int size);
  4066. /** Creates a String from a printf-style parameter list.
  4067. I don't like this method. I don't use it myself, and I recommend avoiding it and
  4068. using the operator<< methods or pretty much anything else instead. It's only provided
  4069. here because of the popular unrest that was stirred-up when I tried to remove it...
  4070. If you're really determined to use it, at least make sure that you never, ever,
  4071. pass any String objects to it as parameters. And bear in mind that internally, depending
  4072. on the platform, it may be using wchar_t or char character types, so that even string
  4073. literals can't be safely used as parameters if you're writing portable code.
  4074. */
  4075. static String formatted (const String formatString, ... );
  4076. // Numeric conversions..
  4077. /** Creates a string containing this signed 32-bit integer as a decimal number.
  4078. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4079. */
  4080. explicit String (int decimalInteger);
  4081. /** Creates a string containing this unsigned 32-bit integer as a decimal number.
  4082. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4083. */
  4084. explicit String (unsigned int decimalInteger);
  4085. /** Creates a string containing this signed 16-bit integer as a decimal number.
  4086. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4087. */
  4088. explicit String (short decimalInteger);
  4089. /** Creates a string containing this unsigned 16-bit integer as a decimal number.
  4090. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4091. */
  4092. explicit String (unsigned short decimalInteger);
  4093. /** Creates a string containing this signed 64-bit integer as a decimal number.
  4094. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  4095. */
  4096. explicit String (int64 largeIntegerValue);
  4097. /** Creates a string containing this unsigned 64-bit integer as a decimal number.
  4098. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  4099. */
  4100. explicit String (uint64 largeIntegerValue);
  4101. /** Creates a string representing this floating-point number.
  4102. @param floatValue the value to convert to a string
  4103. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  4104. decimal places, and will not use exponent notation. If 0 or
  4105. less, it will use exponent notation if necessary.
  4106. @see getDoubleValue, getIntValue
  4107. */
  4108. explicit String (float floatValue,
  4109. int numberOfDecimalPlaces = 0);
  4110. /** Creates a string representing this floating-point number.
  4111. @param doubleValue the value to convert to a string
  4112. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  4113. decimal places, and will not use exponent notation. If 0 or
  4114. less, it will use exponent notation if necessary.
  4115. @see getFloatValue, getIntValue
  4116. */
  4117. explicit String (double doubleValue,
  4118. int numberOfDecimalPlaces = 0);
  4119. /** Reads the value of the string as a decimal number (up to 32 bits in size).
  4120. @returns the value of the string as a 32 bit signed base-10 integer.
  4121. @see getTrailingIntValue, getHexValue32, getHexValue64
  4122. */
  4123. int getIntValue() const noexcept;
  4124. /** Reads the value of the string as a decimal number (up to 64 bits in size).
  4125. @returns the value of the string as a 64 bit signed base-10 integer.
  4126. */
  4127. int64 getLargeIntValue() const noexcept;
  4128. /** Parses a decimal number from the end of the string.
  4129. This will look for a value at the end of the string.
  4130. e.g. for "321 xyz654" it will return 654; for "2 3 4" it'll return 4.
  4131. Negative numbers are not handled, so "xyz-5" returns 5.
  4132. @see getIntValue
  4133. */
  4134. int getTrailingIntValue() const noexcept;
  4135. /** Parses this string as a floating point number.
  4136. @returns the value of the string as a 32-bit floating point value.
  4137. @see getDoubleValue
  4138. */
  4139. float getFloatValue() const noexcept;
  4140. /** Parses this string as a floating point number.
  4141. @returns the value of the string as a 64-bit floating point value.
  4142. @see getFloatValue
  4143. */
  4144. double getDoubleValue() const noexcept;
  4145. /** Parses the string as a hexadecimal number.
  4146. Non-hexadecimal characters in the string are ignored.
  4147. If the string contains too many characters, then the lowest significant
  4148. digits are returned, e.g. "ffff12345678" would produce 0x12345678.
  4149. @returns a 32-bit number which is the value of the string in hex.
  4150. */
  4151. int getHexValue32() const noexcept;
  4152. /** Parses the string as a hexadecimal number.
  4153. Non-hexadecimal characters in the string are ignored.
  4154. If the string contains too many characters, then the lowest significant
  4155. digits are returned, e.g. "ffff1234567812345678" would produce 0x1234567812345678.
  4156. @returns a 64-bit number which is the value of the string in hex.
  4157. */
  4158. int64 getHexValue64() const noexcept;
  4159. /** Creates a string representing this 32-bit value in hexadecimal. */
  4160. static String toHexString (int number);
  4161. /** Creates a string representing this 64-bit value in hexadecimal. */
  4162. static String toHexString (int64 number);
  4163. /** Creates a string representing this 16-bit value in hexadecimal. */
  4164. static String toHexString (short number);
  4165. /** Creates a string containing a hex dump of a block of binary data.
  4166. @param data the binary data to use as input
  4167. @param size how many bytes of data to use
  4168. @param groupSize how many bytes are grouped together before inserting a
  4169. space into the output. e.g. group size 0 has no spaces,
  4170. group size 1 looks like: "be a1 c2 ff", group size 2 looks
  4171. like "bea1 c2ff".
  4172. */
  4173. static String toHexString (const void* data, int size, int groupSize = 1);
  4174. /** Returns the character pointer currently being used to store this string.
  4175. Because it returns a reference to the string's internal data, the pointer
  4176. that is returned must not be stored anywhere, as it can be deleted whenever the
  4177. string changes.
  4178. */
  4179. inline const CharPointerType& getCharPointer() const noexcept { return text; }
  4180. /** Returns a pointer to a UTF-8 version of this string.
  4181. Because it returns a reference to the string's internal data, the pointer
  4182. that is returned must not be stored anywhere, as it can be deleted whenever the
  4183. string changes.
  4184. To find out how many bytes you need to store this string as UTF-8, you can call
  4185. CharPointer_UTF8::getBytesRequiredFor (myString.getCharPointer())
  4186. @see getCharPointer, toUTF16, toUTF32
  4187. */
  4188. const CharPointer_UTF8 toUTF8() const;
  4189. /** Returns a pointer to a UTF-32 version of this string.
  4190. Because it returns a reference to the string's internal data, the pointer
  4191. that is returned must not be stored anywhere, as it can be deleted whenever the
  4192. string changes.
  4193. To find out how many bytes you need to store this string as UTF-16, you can call
  4194. CharPointer_UTF16::getBytesRequiredFor (myString.getCharPointer())
  4195. @see getCharPointer, toUTF8, toUTF32
  4196. */
  4197. CharPointer_UTF16 toUTF16() const;
  4198. /** Returns a pointer to a UTF-32 version of this string.
  4199. Because it returns a reference to the string's internal data, the pointer
  4200. that is returned must not be stored anywhere, as it can be deleted whenever the
  4201. string changes.
  4202. @see getCharPointer, toUTF8, toUTF16
  4203. */
  4204. CharPointer_UTF32 toUTF32() const;
  4205. /** Returns a pointer to a wchar_t version of this string.
  4206. Because it returns a reference to the string's internal data, the pointer
  4207. that is returned must not be stored anywhere, as it can be deleted whenever the
  4208. string changes.
  4209. Bear in mind that the wchar_t type is different on different platforms, so on
  4210. Windows, this will be equivalent to calling toUTF16(), on unix it'll be the same
  4211. as calling toUTF32(), etc.
  4212. @see getCharPointer, toUTF8, toUTF16, toUTF32
  4213. */
  4214. const wchar_t* toWideCharPointer() const;
  4215. /** Creates a String from a UTF-8 encoded buffer.
  4216. If the size is < 0, it'll keep reading until it hits a zero.
  4217. */
  4218. static String fromUTF8 (const char* utf8buffer, int bufferSizeBytes = -1);
  4219. /** Returns the number of bytes required to represent this string as UTF8.
  4220. The number returned does NOT include the trailing zero.
  4221. @see toUTF8, copyToUTF8
  4222. */
  4223. int getNumBytesAsUTF8() const noexcept;
  4224. /** Copies the string to a buffer as UTF-8 characters.
  4225. Returns the number of bytes copied to the buffer, including the terminating null
  4226. character.
  4227. To find out how many bytes you need to store this string as UTF-8, you can call
  4228. CharPointer_UTF8::getBytesRequiredFor (myString.getCharPointer())
  4229. @param destBuffer the place to copy it to; if this is a null pointer, the method just
  4230. returns the number of bytes required (including the terminating null character).
  4231. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll
  4232. put in as many as it can while still allowing for a terminating null char at the
  4233. end, and will return the number of bytes that were actually used.
  4234. @see CharPointer_UTF8::writeWithDestByteLimit
  4235. */
  4236. int copyToUTF8 (CharPointer_UTF8::CharType* destBuffer, int maxBufferSizeBytes) const noexcept;
  4237. /** Copies the string to a buffer as UTF-16 characters.
  4238. Returns the number of bytes copied to the buffer, including the terminating null
  4239. character.
  4240. To find out how many bytes you need to store this string as UTF-16, you can call
  4241. CharPointer_UTF16::getBytesRequiredFor (myString.getCharPointer())
  4242. @param destBuffer the place to copy it to; if this is a null pointer, the method just
  4243. returns the number of bytes required (including the terminating null character).
  4244. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll
  4245. put in as many as it can while still allowing for a terminating null char at the
  4246. end, and will return the number of bytes that were actually used.
  4247. @see CharPointer_UTF16::writeWithDestByteLimit
  4248. */
  4249. int copyToUTF16 (CharPointer_UTF16::CharType* destBuffer, int maxBufferSizeBytes) const noexcept;
  4250. /** Copies the string to a buffer as UTF-16 characters.
  4251. Returns the number of bytes copied to the buffer, including the terminating null
  4252. character.
  4253. To find out how many bytes you need to store this string as UTF-32, you can call
  4254. CharPointer_UTF32::getBytesRequiredFor (myString.getCharPointer())
  4255. @param destBuffer the place to copy it to; if this is a null pointer, the method just
  4256. returns the number of bytes required (including the terminating null character).
  4257. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll
  4258. put in as many as it can while still allowing for a terminating null char at the
  4259. end, and will return the number of bytes that were actually used.
  4260. @see CharPointer_UTF32::writeWithDestByteLimit
  4261. */
  4262. int copyToUTF32 (CharPointer_UTF32::CharType* destBuffer, int maxBufferSizeBytes) const noexcept;
  4263. /** Increases the string's internally allocated storage.
  4264. Although the string's contents won't be affected by this call, it will
  4265. increase the amount of memory allocated internally for the string to grow into.
  4266. If you're about to make a large number of calls to methods such
  4267. as += or <<, it's more efficient to preallocate enough extra space
  4268. beforehand, so that these methods won't have to keep resizing the string
  4269. to append the extra characters.
  4270. @param numBytesNeeded the number of bytes to allocate storage for. If this
  4271. value is less than the currently allocated size, it will
  4272. have no effect.
  4273. */
  4274. void preallocateBytes (size_t numBytesNeeded);
  4275. /** Swaps the contents of this string with another one.
  4276. This is a very fast operation, as no allocation or copying needs to be done.
  4277. */
  4278. void swapWith (String& other) noexcept;
  4279. /** A helper class to improve performance when concatenating many large strings
  4280. together.
  4281. Because appending one string to another involves measuring the length of
  4282. both strings, repeatedly doing this for many long strings will become
  4283. an exponentially slow operation. This class uses some internal state to
  4284. avoid that, so that each append operation only needs to measure the length
  4285. of the appended string.
  4286. */
  4287. class JUCE_API Concatenator
  4288. {
  4289. public:
  4290. Concatenator (String& stringToAppendTo);
  4291. ~Concatenator();
  4292. void append (const String& s);
  4293. private:
  4294. String& result;
  4295. int nextIndex;
  4296. JUCE_DECLARE_NON_COPYABLE (Concatenator);
  4297. };
  4298. #if JUCE_MAC || JUCE_IOS || DOXYGEN
  4299. /** MAC ONLY - Creates a String from an OSX CFString. */
  4300. static String fromCFString (CFStringRef cfString);
  4301. /** MAC ONLY - Converts this string to a CFString.
  4302. Remember that you must use CFRelease() to free the returned string when you're
  4303. finished with it.
  4304. */
  4305. CFStringRef toCFString() const;
  4306. /** MAC ONLY - Returns a copy of this string in which any decomposed unicode characters have
  4307. been converted to their precomposed equivalents. */
  4308. String convertToPrecomposedUnicode() const;
  4309. #endif
  4310. private:
  4311. CharPointerType text;
  4312. struct PreallocationBytes
  4313. {
  4314. explicit PreallocationBytes (size_t);
  4315. size_t numBytes;
  4316. };
  4317. explicit String (const PreallocationBytes&); // This constructor preallocates a certain amount of memory
  4318. void appendFixedLength (const char* text, int numExtraChars);
  4319. size_t getByteOffsetOfEnd() const noexcept;
  4320. JUCE_DEPRECATED (String (const String& stringToCopy, size_t charsToAllocate));
  4321. // This private cast operator should prevent strings being accidentally cast
  4322. // to bools (this is possible because the compiler can add an implicit cast
  4323. // via a const char*)
  4324. operator bool() const noexcept { return false; }
  4325. };
  4326. /** Concatenates two strings. */
  4327. JUCE_API String JUCE_CALLTYPE operator+ (const char* string1, const String& string2);
  4328. /** Concatenates two strings. */
  4329. JUCE_API String JUCE_CALLTYPE operator+ (const wchar_t* string1, const String& string2);
  4330. /** Concatenates two strings. */
  4331. JUCE_API String JUCE_CALLTYPE operator+ (char string1, const String& string2);
  4332. /** Concatenates two strings. */
  4333. JUCE_API String JUCE_CALLTYPE operator+ (wchar_t string1, const String& string2);
  4334. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  4335. /** Concatenates two strings. */
  4336. JUCE_API String JUCE_CALLTYPE operator+ (juce_wchar string1, const String& string2);
  4337. #endif
  4338. /** Concatenates two strings. */
  4339. JUCE_API String JUCE_CALLTYPE operator+ (String string1, const String& string2);
  4340. /** Concatenates two strings. */
  4341. JUCE_API String JUCE_CALLTYPE operator+ (String string1, const char* string2);
  4342. /** Concatenates two strings. */
  4343. JUCE_API String JUCE_CALLTYPE operator+ (String string1, const wchar_t* string2);
  4344. /** Concatenates two strings. */
  4345. JUCE_API String JUCE_CALLTYPE operator+ (String string1, char characterToAppend);
  4346. /** Concatenates two strings. */
  4347. JUCE_API String JUCE_CALLTYPE operator+ (String string1, wchar_t characterToAppend);
  4348. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  4349. /** Concatenates two strings. */
  4350. JUCE_API String JUCE_CALLTYPE operator+ (String string1, juce_wchar characterToAppend);
  4351. #endif
  4352. /** Appends a character at the end of a string. */
  4353. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, char characterToAppend);
  4354. /** Appends a character at the end of a string. */
  4355. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, wchar_t characterToAppend);
  4356. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  4357. /** Appends a character at the end of a string. */
  4358. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, juce_wchar characterToAppend);
  4359. #endif
  4360. /** Appends a string to the end of the first one. */
  4361. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char* string2);
  4362. /** Appends a string to the end of the first one. */
  4363. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const wchar_t* string2);
  4364. /** Appends a string to the end of the first one. */
  4365. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const String& string2);
  4366. /** Appends a decimal number at the end of a string. */
  4367. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, short number);
  4368. /** Appends a decimal number at the end of a string. */
  4369. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, int number);
  4370. /** Appends a decimal number at the end of a string. */
  4371. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, long number);
  4372. /** Appends a decimal number at the end of a string. */
  4373. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, float number);
  4374. /** Appends a decimal number at the end of a string. */
  4375. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, double number);
  4376. /** Case-sensitive comparison of two strings. */
  4377. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) noexcept;
  4378. /** Case-sensitive comparison of two strings. */
  4379. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) noexcept;
  4380. /** Case-sensitive comparison of two strings. */
  4381. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const wchar_t* string2) noexcept;
  4382. /** Case-sensitive comparison of two strings. */
  4383. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF8& string2) noexcept;
  4384. /** Case-sensitive comparison of two strings. */
  4385. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF16& string2) noexcept;
  4386. /** Case-sensitive comparison of two strings. */
  4387. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF32& string2) noexcept;
  4388. /** Case-sensitive comparison of two strings. */
  4389. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) noexcept;
  4390. /** Case-sensitive comparison of two strings. */
  4391. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) noexcept;
  4392. /** Case-sensitive comparison of two strings. */
  4393. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const wchar_t* string2) noexcept;
  4394. /** Case-sensitive comparison of two strings. */
  4395. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF8& string2) noexcept;
  4396. /** Case-sensitive comparison of two strings. */
  4397. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF16& string2) noexcept;
  4398. /** Case-sensitive comparison of two strings. */
  4399. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF32& string2) noexcept;
  4400. /** Case-sensitive comparison of two strings. */
  4401. JUCE_API bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) noexcept;
  4402. /** Case-sensitive comparison of two strings. */
  4403. JUCE_API bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) noexcept;
  4404. /** 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 String& string2) noexcept;
  4408. /** This operator allows you to write a juce String directly to std output streams.
  4409. This is handy for writing strings to std::cout, std::cerr, etc.
  4410. */
  4411. template <class traits>
  4412. std::basic_ostream <char, traits>& JUCE_CALLTYPE operator<< (std::basic_ostream <char, traits>& stream, const String& stringToWrite)
  4413. {
  4414. return stream << stringToWrite.toUTF8().getAddress();
  4415. }
  4416. /** This operator allows you to write a juce String directly to std output streams.
  4417. This is handy for writing strings to std::wcout, std::wcerr, etc.
  4418. */
  4419. template <class traits>
  4420. std::basic_ostream <wchar_t, traits>& JUCE_CALLTYPE operator<< (std::basic_ostream <wchar_t, traits>& stream, const String& stringToWrite)
  4421. {
  4422. return stream << stringToWrite.toWideCharPointer();
  4423. }
  4424. /** Writes a string to an OutputStream as UTF8. */
  4425. JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& stringToWrite);
  4426. #endif // __JUCE_STRING_JUCEHEADER__
  4427. /*** End of inlined file: juce_String.h ***/
  4428. /**
  4429. Acts as an application-wide logging class.
  4430. A subclass of Logger can be created and passed into the Logger::setCurrentLogger
  4431. method and this will then be used by all calls to writeToLog.
  4432. The logger class also contains methods for writing messages to the debugger's
  4433. output stream.
  4434. @see FileLogger
  4435. */
  4436. class JUCE_API Logger
  4437. {
  4438. public:
  4439. /** Destructor. */
  4440. virtual ~Logger();
  4441. /** Sets the current logging class to use.
  4442. Note that the object passed in won't be deleted when no longer needed.
  4443. A null pointer can be passed-in to disable any logging.
  4444. If deleteOldLogger is set to true, the existing logger will be
  4445. deleted (if there is one).
  4446. */
  4447. static void JUCE_CALLTYPE setCurrentLogger (Logger* newLogger,
  4448. bool deleteOldLogger = false);
  4449. /** Writes a string to the current logger.
  4450. This will pass the string to the logger's logMessage() method if a logger
  4451. has been set.
  4452. @see logMessage
  4453. */
  4454. static void JUCE_CALLTYPE writeToLog (const String& message);
  4455. /** Writes a message to the standard error stream.
  4456. This can be called directly, or by using the DBG() macro in
  4457. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  4458. */
  4459. static void JUCE_CALLTYPE outputDebugString (const String& text);
  4460. protected:
  4461. Logger();
  4462. /** This is overloaded by subclasses to implement custom logging behaviour.
  4463. @see setCurrentLogger
  4464. */
  4465. virtual void logMessage (const String& message) = 0;
  4466. private:
  4467. static Logger* currentLogger;
  4468. };
  4469. #endif // __JUCE_LOGGER_JUCEHEADER__
  4470. /*** End of inlined file: juce_Logger.h ***/
  4471. /*** Start of inlined file: juce_LeakedObjectDetector.h ***/
  4472. #ifndef __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  4473. #define __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  4474. /**
  4475. Embedding an instance of this class inside another class can be used as a low-overhead
  4476. way of detecting leaked instances.
  4477. This class keeps an internal static count of the number of instances that are
  4478. active, so that when the app is shutdown and the static destructors are called,
  4479. it can check whether there are any left-over instances that may have been leaked.
  4480. To use it, use the JUCE_LEAK_DETECTOR macro as a simple way to put one in your
  4481. class declaration. Have a look through the juce codebase for examples, it's used
  4482. in most of the classes.
  4483. */
  4484. template <class OwnerClass>
  4485. class LeakedObjectDetector
  4486. {
  4487. public:
  4488. LeakedObjectDetector() noexcept { ++(getCounter().numObjects); }
  4489. LeakedObjectDetector (const LeakedObjectDetector&) noexcept { ++(getCounter().numObjects); }
  4490. ~LeakedObjectDetector()
  4491. {
  4492. if (--(getCounter().numObjects) < 0)
  4493. {
  4494. DBG ("*** Dangling pointer deletion! Class: " << getLeakedObjectClassName());
  4495. /** If you hit this, then you've managed to delete more instances of this class than you've
  4496. created.. That indicates that you're deleting some dangling pointers.
  4497. Note that although this assertion will have been triggered during a destructor, it might
  4498. not be this particular deletion that's at fault - the incorrect one may have happened
  4499. at an earlier point in the program, and simply not been detected until now.
  4500. Most errors like this are caused by using old-fashioned, non-RAII techniques for
  4501. your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays,
  4502. ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs!
  4503. */
  4504. jassertfalse;
  4505. }
  4506. }
  4507. private:
  4508. class LeakCounter
  4509. {
  4510. public:
  4511. LeakCounter() noexcept {}
  4512. ~LeakCounter()
  4513. {
  4514. if (numObjects.value > 0)
  4515. {
  4516. DBG ("*** Leaked objects detected: " << numObjects.value << " instance(s) of class " << getLeakedObjectClassName());
  4517. /** If you hit this, then you've leaked one or more objects of the type specified by
  4518. the 'OwnerClass' template parameter - the name should have been printed by the line above.
  4519. If you're leaking, it's probably because you're using old-fashioned, non-RAII techniques for
  4520. your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays,
  4521. ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs!
  4522. */
  4523. jassertfalse;
  4524. }
  4525. }
  4526. Atomic<int> numObjects;
  4527. };
  4528. static const char* getLeakedObjectClassName()
  4529. {
  4530. return OwnerClass::getLeakedObjectClassName();
  4531. }
  4532. static LeakCounter& getCounter() noexcept
  4533. {
  4534. static LeakCounter counter;
  4535. return counter;
  4536. }
  4537. };
  4538. #if DOXYGEN || ! defined (JUCE_LEAK_DETECTOR)
  4539. #if (DOXYGEN || JUCE_CHECK_MEMORY_LEAKS)
  4540. /** This macro lets you embed a leak-detecting object inside a class.
  4541. To use it, simply declare a JUCE_LEAK_DETECTOR(YourClassName) inside a private section
  4542. of the class declaration. E.g.
  4543. @code
  4544. class MyClass
  4545. {
  4546. public:
  4547. MyClass();
  4548. void blahBlah();
  4549. private:
  4550. JUCE_LEAK_DETECTOR (MyClass);
  4551. };@endcode
  4552. @see JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR, LeakedObjectDetector
  4553. */
  4554. #define JUCE_LEAK_DETECTOR(OwnerClass) \
  4555. friend class JUCE_NAMESPACE::LeakedObjectDetector<OwnerClass>; \
  4556. static const char* getLeakedObjectClassName() noexcept { return #OwnerClass; } \
  4557. JUCE_NAMESPACE::LeakedObjectDetector<OwnerClass> JUCE_JOIN_MACRO (leakDetector, __LINE__);
  4558. #else
  4559. #define JUCE_LEAK_DETECTOR(OwnerClass)
  4560. #endif
  4561. #endif
  4562. #endif // __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  4563. /*** End of inlined file: juce_LeakedObjectDetector.h ***/
  4564. #undef TYPE_BOOL // (stupidly-named CoreServices definition which interferes with other libraries).
  4565. #if JUCE_MAC || JUCE_IOS || DOXYGEN
  4566. /** A handy C++ wrapper that creates and deletes an NSAutoreleasePool object using RAII. */
  4567. class JUCE_API ScopedAutoReleasePool
  4568. {
  4569. public:
  4570. ScopedAutoReleasePool();
  4571. ~ScopedAutoReleasePool();
  4572. private:
  4573. void* pool;
  4574. JUCE_DECLARE_NON_COPYABLE (ScopedAutoReleasePool);
  4575. };
  4576. /** A macro that can be used to easily declare a local ScopedAutoReleasePool object for RAII-based obj-C autoreleasing. */
  4577. #define JUCE_AUTORELEASEPOOL const JUCE_NAMESPACE::ScopedAutoReleasePool JUCE_JOIN_MACRO (autoReleasePool_, __LINE__);
  4578. #else
  4579. #define JUCE_AUTORELEASEPOOL
  4580. #endif
  4581. END_JUCE_NAMESPACE
  4582. #endif // __JUCE_STANDARDHEADER_JUCEHEADER__
  4583. /*** End of inlined file: juce_StandardHeader.h ***/
  4584. BEGIN_JUCE_NAMESPACE
  4585. #if JUCE_MSVC
  4586. // this is set explicitly in case the app is using a different packing size.
  4587. #pragma pack (push, 8)
  4588. #pragma warning (push)
  4589. #pragma warning (disable: 4786) // (old vc6 warning about long class names)
  4590. #ifdef __INTEL_COMPILER
  4591. #pragma warning (disable: 1125)
  4592. #endif
  4593. #endif
  4594. // this is where all the class header files get brought in..
  4595. /*** Start of inlined file: juce_core_includes.h ***/
  4596. #ifndef __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  4597. #define __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  4598. #ifndef __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4599. /*** Start of inlined file: juce_AbstractFifo.h ***/
  4600. #ifndef __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4601. #define __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4602. /**
  4603. Encapsulates the logic required to implement a lock-free FIFO.
  4604. This class handles the logic needed when building a single-reader, single-writer FIFO.
  4605. It doesn't actually hold any data itself, but your FIFO class can use one of these to manage
  4606. its position and status when reading or writing to it.
  4607. To use it, you can call prepareToWrite() to determine the position within your own buffer that
  4608. an incoming block of data should be stored, and prepareToRead() to find out when the next
  4609. outgoing block should be read from.
  4610. e.g.
  4611. @code
  4612. class MyFifo
  4613. {
  4614. public:
  4615. MyFifo() : abstractFifo (1024)
  4616. {
  4617. }
  4618. void addToFifo (const int* someData, int numItems)
  4619. {
  4620. int start1, size1, start2, size2;
  4621. prepareToWrite (numItems, start1, size1, start2, size2);
  4622. if (size1 > 0)
  4623. copySomeData (myBuffer + start1, someData, size1);
  4624. if (size2 > 0)
  4625. copySomeData (myBuffer + start2, someData + size1, size2);
  4626. finishedWrite (size1 + size2);
  4627. }
  4628. void readFromFifo (int* someData, int numItems)
  4629. {
  4630. int start1, size1, start2, size2;
  4631. prepareToRead (numSamples, start1, size1, start2, size2);
  4632. if (size1 > 0)
  4633. copySomeData (someData, myBuffer + start1, size1);
  4634. if (size2 > 0)
  4635. copySomeData (someData + size1, myBuffer + start2, size2);
  4636. finishedRead (size1 + size2);
  4637. }
  4638. private:
  4639. AbstractFifo abstractFifo;
  4640. int myBuffer [1024];
  4641. };
  4642. @endcode
  4643. */
  4644. class JUCE_API AbstractFifo
  4645. {
  4646. public:
  4647. /** Creates a FIFO to manage a buffer with the specified capacity. */
  4648. AbstractFifo (int capacity) noexcept;
  4649. /** Destructor */
  4650. ~AbstractFifo();
  4651. /** Returns the total size of the buffer being managed. */
  4652. int getTotalSize() const noexcept;
  4653. /** Returns the number of items that can currently be added to the buffer without it overflowing. */
  4654. int getFreeSpace() const noexcept;
  4655. /** Returns the number of items that can currently be read from the buffer. */
  4656. int getNumReady() const noexcept;
  4657. /** Clears the buffer positions, so that it appears empty. */
  4658. void reset() noexcept;
  4659. /** Changes the buffer's total size.
  4660. Note that this isn't thread-safe, so don't call it if there's any danger that it
  4661. might overlap with a call to any other method in this class!
  4662. */
  4663. void setTotalSize (int newSize) noexcept;
  4664. /** Returns the location within the buffer at which an incoming block of data should be written.
  4665. Because the section of data that you want to add to the buffer may overlap the end
  4666. and wrap around to the start, two blocks within your buffer are returned, and you
  4667. should copy your data into the first one, with any remaining data spilling over into
  4668. the second.
  4669. If the number of items you ask for is too large to fit within the buffer's free space, then
  4670. blockSize1 + blockSize2 may add up to a lower value than numToWrite. If this happens, you
  4671. may decide to keep waiting and re-trying the method until there's enough space available.
  4672. After calling this method, if you choose to write your data into the blocks returned, you
  4673. must call finishedWrite() to tell the FIFO how much data you actually added.
  4674. e.g.
  4675. @code
  4676. void addToFifo (const int* someData, int numItems)
  4677. {
  4678. int start1, size1, start2, size2;
  4679. prepareToWrite (numItems, start1, size1, start2, size2);
  4680. if (size1 > 0)
  4681. copySomeData (myBuffer + start1, someData, size1);
  4682. if (size2 > 0)
  4683. copySomeData (myBuffer + start2, someData + size1, size2);
  4684. finishedWrite (size1 + size2);
  4685. }
  4686. @endcode
  4687. @param numToWrite indicates how many items you'd like to add to the buffer
  4688. @param startIndex1 on exit, this will contain the start index in your buffer at which your data should be written
  4689. @param blockSize1 on exit, this indicates how many items can be written to the block starting at startIndex1
  4690. @param startIndex2 on exit, this will contain the start index in your buffer at which any data that didn't fit into
  4691. the first block should be written
  4692. @param blockSize2 on exit, this indicates how many items can be written to the block starting at startIndex2
  4693. @see finishedWrite
  4694. */
  4695. void prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const noexcept;
  4696. /** Called after reading from the FIFO, to indicate that this many items have been added.
  4697. @see prepareToWrite
  4698. */
  4699. void finishedWrite (int numWritten) noexcept;
  4700. /** Returns the location within the buffer from which the next block of data should be read.
  4701. Because the section of data that you want to read from the buffer may overlap the end
  4702. and wrap around to the start, two blocks within your buffer are returned, and you
  4703. should read from both of them.
  4704. If the number of items you ask for is greater than the amount of data available, then
  4705. blockSize1 + blockSize2 may add up to a lower value than numWanted. If this happens, you
  4706. may decide to keep waiting and re-trying the method until there's enough data available.
  4707. After calling this method, if you choose to read the data, you must call finishedRead() to
  4708. tell the FIFO how much data you have consumed.
  4709. e.g.
  4710. @code
  4711. void readFromFifo (int* someData, int numItems)
  4712. {
  4713. int start1, size1, start2, size2;
  4714. prepareToRead (numSamples, start1, size1, start2, size2);
  4715. if (size1 > 0)
  4716. copySomeData (someData, myBuffer + start1, size1);
  4717. if (size2 > 0)
  4718. copySomeData (someData + size1, myBuffer + start2, size2);
  4719. finishedRead (size1 + size2);
  4720. }
  4721. @endcode
  4722. @param numWanted indicates how many items you'd like to add to the buffer
  4723. @param startIndex1 on exit, this will contain the start index in your buffer at which your data should be written
  4724. @param blockSize1 on exit, this indicates how many items can be written to the block starting at startIndex1
  4725. @param startIndex2 on exit, this will contain the start index in your buffer at which any data that didn't fit into
  4726. the first block should be written
  4727. @param blockSize2 on exit, this indicates how many items can be written to the block starting at startIndex2
  4728. @see finishedRead
  4729. */
  4730. void prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const noexcept;
  4731. /** Called after reading from the FIFO, to indicate that this many items have now been consumed.
  4732. @see prepareToRead
  4733. */
  4734. void finishedRead (int numRead) noexcept;
  4735. private:
  4736. int bufferSize;
  4737. Atomic <int> validStart, validEnd;
  4738. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AbstractFifo);
  4739. };
  4740. #endif // __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4741. /*** End of inlined file: juce_AbstractFifo.h ***/
  4742. #endif
  4743. #ifndef __JUCE_ARRAY_JUCEHEADER__
  4744. /*** Start of inlined file: juce_Array.h ***/
  4745. #ifndef __JUCE_ARRAY_JUCEHEADER__
  4746. #define __JUCE_ARRAY_JUCEHEADER__
  4747. /*** Start of inlined file: juce_ArrayAllocationBase.h ***/
  4748. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  4749. #define __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  4750. /*** Start of inlined file: juce_HeapBlock.h ***/
  4751. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  4752. #define __JUCE_HEAPBLOCK_JUCEHEADER__
  4753. /**
  4754. Very simple container class to hold a pointer to some data on the heap.
  4755. When you need to allocate some heap storage for something, always try to use
  4756. this class instead of allocating the memory directly using malloc/free.
  4757. A HeapBlock<char> object can be treated in pretty much exactly the same way
  4758. as an char*, but as long as you allocate it on the stack or as a class member,
  4759. it's almost impossible for it to leak memory.
  4760. It also makes your code much more concise and readable than doing the same thing
  4761. using direct allocations,
  4762. E.g. instead of this:
  4763. @code
  4764. int* temp = (int*) malloc (1024 * sizeof (int));
  4765. memcpy (temp, xyz, 1024 * sizeof (int));
  4766. free (temp);
  4767. temp = (int*) calloc (2048 * sizeof (int));
  4768. temp[0] = 1234;
  4769. memcpy (foobar, temp, 2048 * sizeof (int));
  4770. free (temp);
  4771. @endcode
  4772. ..you could just write this:
  4773. @code
  4774. HeapBlock <int> temp (1024);
  4775. memcpy (temp, xyz, 1024 * sizeof (int));
  4776. temp.calloc (2048);
  4777. temp[0] = 1234;
  4778. memcpy (foobar, temp, 2048 * sizeof (int));
  4779. @endcode
  4780. The class is extremely lightweight, containing only a pointer to the
  4781. data, and exposes malloc/realloc/calloc/free methods that do the same jobs
  4782. as their less object-oriented counterparts. Despite adding safety, you probably
  4783. won't sacrifice any performance by using this in place of normal pointers.
  4784. @see Array, OwnedArray, MemoryBlock
  4785. */
  4786. template <class ElementType>
  4787. class HeapBlock
  4788. {
  4789. public:
  4790. /** Creates a HeapBlock which is initially just a null pointer.
  4791. After creation, you can resize the array using the malloc(), calloc(),
  4792. or realloc() methods.
  4793. */
  4794. HeapBlock() noexcept : data (nullptr)
  4795. {
  4796. }
  4797. /** Creates a HeapBlock containing a number of elements.
  4798. The contents of the block are undefined, as it will have been created by a
  4799. malloc call.
  4800. If you want an array of zero values, you can use the calloc() method instead.
  4801. */
  4802. explicit HeapBlock (const size_t numElements)
  4803. : data (static_cast <ElementType*> (::malloc (numElements * sizeof (ElementType))))
  4804. {
  4805. }
  4806. /** Destructor.
  4807. This will free the data, if any has been allocated.
  4808. */
  4809. ~HeapBlock()
  4810. {
  4811. ::free (data);
  4812. }
  4813. /** Returns a raw pointer to the allocated data.
  4814. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4815. freed by calling the free() method.
  4816. */
  4817. inline operator ElementType*() const noexcept { return data; }
  4818. /** Returns a raw pointer to the allocated data.
  4819. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4820. freed by calling the free() method.
  4821. */
  4822. inline ElementType* getData() const noexcept { return data; }
  4823. /** Returns a void pointer to the allocated data.
  4824. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4825. freed by calling the free() method.
  4826. */
  4827. inline operator void*() const noexcept { return static_cast <void*> (data); }
  4828. /** Returns a void pointer to the allocated data.
  4829. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4830. freed by calling the free() method.
  4831. */
  4832. inline operator const void*() const noexcept { return static_cast <const void*> (data); }
  4833. /** Lets you use indirect calls to the first element in the array.
  4834. Obviously this will cause problems if the array hasn't been initialised, because it'll
  4835. be referencing a null pointer.
  4836. */
  4837. inline ElementType* operator->() const noexcept { return data; }
  4838. /** Returns a reference to one of the data elements.
  4839. Obviously there's no bounds-checking here, as this object is just a dumb pointer and
  4840. has no idea of the size it currently has allocated.
  4841. */
  4842. template <typename IndexType>
  4843. inline ElementType& operator[] (IndexType index) const noexcept { return data [index]; }
  4844. /** Returns a pointer to a data element at an offset from the start of the array.
  4845. This is the same as doing pointer arithmetic on the raw pointer itself.
  4846. */
  4847. template <typename IndexType>
  4848. inline ElementType* operator+ (IndexType index) const noexcept { return data + index; }
  4849. /** Compares the pointer with another pointer.
  4850. This can be handy for checking whether this is a null pointer.
  4851. */
  4852. inline bool operator== (const ElementType* const otherPointer) const noexcept { return otherPointer == data; }
  4853. /** Compares the pointer with another pointer.
  4854. This can be handy for checking whether this is a null pointer.
  4855. */
  4856. inline bool operator!= (const ElementType* const otherPointer) const noexcept { return otherPointer != data; }
  4857. /** Allocates a specified amount of memory.
  4858. This uses the normal malloc to allocate an amount of memory for this object.
  4859. Any previously allocated memory will be freed by this method.
  4860. The number of bytes allocated will be (newNumElements * elementSize). Normally
  4861. you wouldn't need to specify the second parameter, but it can be handy if you need
  4862. to allocate a size in bytes rather than in terms of the number of elements.
  4863. The data that is allocated will be freed when this object is deleted, or when you
  4864. call free() or any of the allocation methods.
  4865. */
  4866. void malloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  4867. {
  4868. ::free (data);
  4869. data = static_cast <ElementType*> (::malloc (newNumElements * elementSize));
  4870. }
  4871. /** Allocates a specified amount of memory and clears it.
  4872. This does the same job as the malloc() method, but clears the memory that it allocates.
  4873. */
  4874. void calloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  4875. {
  4876. ::free (data);
  4877. data = static_cast <ElementType*> (::calloc (newNumElements, elementSize));
  4878. }
  4879. /** Allocates a specified amount of memory and optionally clears it.
  4880. This does the same job as either malloc() or calloc(), depending on the
  4881. initialiseToZero parameter.
  4882. */
  4883. void allocate (const size_t newNumElements, const bool initialiseToZero)
  4884. {
  4885. ::free (data);
  4886. if (initialiseToZero)
  4887. data = static_cast <ElementType*> (::calloc (newNumElements, sizeof (ElementType)));
  4888. else
  4889. data = static_cast <ElementType*> (::malloc (newNumElements * sizeof (ElementType)));
  4890. }
  4891. /** Re-allocates a specified amount of memory.
  4892. The semantics of this method are the same as malloc() and calloc(), but it
  4893. uses realloc() to keep as much of the existing data as possible.
  4894. */
  4895. void realloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  4896. {
  4897. if (data == nullptr)
  4898. data = static_cast <ElementType*> (::malloc (newNumElements * elementSize));
  4899. else
  4900. data = static_cast <ElementType*> (::realloc (data, newNumElements * elementSize));
  4901. }
  4902. /** Frees any currently-allocated data.
  4903. This will free the data and reset this object to be a null pointer.
  4904. */
  4905. void free()
  4906. {
  4907. ::free (data);
  4908. data = nullptr;
  4909. }
  4910. /** Swaps this object's data with the data of another HeapBlock.
  4911. The two objects simply exchange their data pointers.
  4912. */
  4913. void swapWith (HeapBlock <ElementType>& other) noexcept
  4914. {
  4915. std::swap (data, other.data);
  4916. }
  4917. /** This fills the block with zeros, up to the number of elements specified.
  4918. Since the block has no way of knowing its own size, you must make sure that the number of
  4919. elements you specify doesn't exceed the allocated size.
  4920. */
  4921. void clear (size_t numElements) noexcept
  4922. {
  4923. zeromem (data, sizeof (ElementType) * numElements);
  4924. }
  4925. private:
  4926. ElementType* data;
  4927. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HeapBlock);
  4928. };
  4929. #endif // __JUCE_HEAPBLOCK_JUCEHEADER__
  4930. /*** End of inlined file: juce_HeapBlock.h ***/
  4931. /**
  4932. Implements some basic array storage allocation functions.
  4933. This class isn't really for public use - it's used by the other
  4934. array classes, but might come in handy for some purposes.
  4935. It inherits from a critical section class to allow the arrays to use
  4936. the "empty base class optimisation" pattern to reduce their footprint.
  4937. @see Array, OwnedArray, ReferenceCountedArray
  4938. */
  4939. template <class ElementType, class TypeOfCriticalSectionToUse>
  4940. class ArrayAllocationBase : public TypeOfCriticalSectionToUse
  4941. {
  4942. public:
  4943. /** Creates an empty array. */
  4944. ArrayAllocationBase() noexcept
  4945. : numAllocated (0)
  4946. {
  4947. }
  4948. /** Destructor. */
  4949. ~ArrayAllocationBase()
  4950. {
  4951. }
  4952. /** Changes the amount of storage allocated.
  4953. This will retain any data currently held in the array, and either add or
  4954. remove extra space at the end.
  4955. @param numElements the number of elements that are needed
  4956. */
  4957. void setAllocatedSize (const int numElements)
  4958. {
  4959. if (numAllocated != numElements)
  4960. {
  4961. if (numElements > 0)
  4962. elements.realloc (numElements);
  4963. else
  4964. elements.free();
  4965. numAllocated = numElements;
  4966. }
  4967. }
  4968. /** Increases the amount of storage allocated if it is less than a given amount.
  4969. This will retain any data currently held in the array, but will add
  4970. extra space at the end to make sure there it's at least as big as the size
  4971. passed in. If it's already bigger, no action is taken.
  4972. @param minNumElements the minimum number of elements that are needed
  4973. */
  4974. void ensureAllocatedSize (const int minNumElements)
  4975. {
  4976. if (minNumElements > numAllocated)
  4977. setAllocatedSize ((minNumElements + minNumElements / 2 + 8) & ~7);
  4978. }
  4979. /** Minimises the amount of storage allocated so that it's no more than
  4980. the given number of elements.
  4981. */
  4982. void shrinkToNoMoreThan (const int maxNumElements)
  4983. {
  4984. if (maxNumElements < numAllocated)
  4985. setAllocatedSize (maxNumElements);
  4986. }
  4987. /** Swap the contents of two objects. */
  4988. void swapWith (ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse>& other) noexcept
  4989. {
  4990. elements.swapWith (other.elements);
  4991. std::swap (numAllocated, other.numAllocated);
  4992. }
  4993. HeapBlock <ElementType> elements;
  4994. int numAllocated;
  4995. private:
  4996. JUCE_DECLARE_NON_COPYABLE (ArrayAllocationBase);
  4997. };
  4998. #endif // __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  4999. /*** End of inlined file: juce_ArrayAllocationBase.h ***/
  5000. /*** Start of inlined file: juce_ElementComparator.h ***/
  5001. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  5002. #define __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  5003. /**
  5004. Sorts a range of elements in an array.
  5005. The comparator object that is passed-in must define a public method with the following
  5006. signature:
  5007. @code
  5008. int compareElements (ElementType first, ElementType second);
  5009. @endcode
  5010. ..and this method must return:
  5011. - a value of < 0 if the first comes before the second
  5012. - a value of 0 if the two objects are equivalent
  5013. - a value of > 0 if the second comes before the first
  5014. To improve performance, the compareElements() method can be declared as static or const.
  5015. @param comparator an object which defines a compareElements() method
  5016. @param array the array to sort
  5017. @param firstElement the index of the first element of the range to be sorted
  5018. @param lastElement the index of the last element in the range that needs
  5019. sorting (this is inclusive)
  5020. @param retainOrderOfEquivalentItems if true, the order of items that the
  5021. comparator deems the same will be maintained - this will be
  5022. a slower algorithm than if they are allowed to be moved around.
  5023. @see sortArrayRetainingOrder
  5024. */
  5025. template <class ElementType, class ElementComparator>
  5026. static void sortArray (ElementComparator& comparator,
  5027. ElementType* const array,
  5028. int firstElement,
  5029. int lastElement,
  5030. const bool retainOrderOfEquivalentItems)
  5031. {
  5032. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5033. // avoids getting warning messages about the parameter being unused
  5034. if (lastElement > firstElement)
  5035. {
  5036. if (retainOrderOfEquivalentItems)
  5037. {
  5038. for (int i = firstElement; i < lastElement; ++i)
  5039. {
  5040. if (comparator.compareElements (array[i], array [i + 1]) > 0)
  5041. {
  5042. std::swap (array[i], array[i + 1]);
  5043. if (i > firstElement)
  5044. i -= 2;
  5045. }
  5046. }
  5047. }
  5048. else
  5049. {
  5050. int fromStack[30], toStack[30];
  5051. int stackIndex = 0;
  5052. for (;;)
  5053. {
  5054. const int size = (lastElement - firstElement) + 1;
  5055. if (size <= 8)
  5056. {
  5057. int j = lastElement;
  5058. int maxIndex;
  5059. while (j > firstElement)
  5060. {
  5061. maxIndex = firstElement;
  5062. for (int k = firstElement + 1; k <= j; ++k)
  5063. if (comparator.compareElements (array[k], array [maxIndex]) > 0)
  5064. maxIndex = k;
  5065. std::swap (array[j], array[maxIndex]);
  5066. --j;
  5067. }
  5068. }
  5069. else
  5070. {
  5071. const int mid = firstElement + (size >> 1);
  5072. std::swap (array[mid], array[firstElement]);
  5073. int i = firstElement;
  5074. int j = lastElement + 1;
  5075. for (;;)
  5076. {
  5077. while (++i <= lastElement
  5078. && comparator.compareElements (array[i], array [firstElement]) <= 0)
  5079. {}
  5080. while (--j > firstElement
  5081. && comparator.compareElements (array[j], array [firstElement]) >= 0)
  5082. {}
  5083. if (j < i)
  5084. break;
  5085. std::swap (array[i], array[j]);
  5086. }
  5087. std::swap (array[j], array[firstElement]);
  5088. if (j - 1 - firstElement >= lastElement - i)
  5089. {
  5090. if (firstElement + 1 < j)
  5091. {
  5092. fromStack [stackIndex] = firstElement;
  5093. toStack [stackIndex] = j - 1;
  5094. ++stackIndex;
  5095. }
  5096. if (i < lastElement)
  5097. {
  5098. firstElement = i;
  5099. continue;
  5100. }
  5101. }
  5102. else
  5103. {
  5104. if (i < lastElement)
  5105. {
  5106. fromStack [stackIndex] = i;
  5107. toStack [stackIndex] = lastElement;
  5108. ++stackIndex;
  5109. }
  5110. if (firstElement + 1 < j)
  5111. {
  5112. lastElement = j - 1;
  5113. continue;
  5114. }
  5115. }
  5116. }
  5117. if (--stackIndex < 0)
  5118. break;
  5119. jassert (stackIndex < numElementsInArray (fromStack));
  5120. firstElement = fromStack [stackIndex];
  5121. lastElement = toStack [stackIndex];
  5122. }
  5123. }
  5124. }
  5125. }
  5126. /**
  5127. Searches a sorted array of elements, looking for the index at which a specified value
  5128. should be inserted for it to be in the correct order.
  5129. The comparator object that is passed-in must define a public method with the following
  5130. signature:
  5131. @code
  5132. int compareElements (ElementType first, ElementType second);
  5133. @endcode
  5134. ..and this method must return:
  5135. - a value of < 0 if the first comes before the second
  5136. - a value of 0 if the two objects are equivalent
  5137. - a value of > 0 if the second comes before the first
  5138. To improve performance, the compareElements() method can be declared as static or const.
  5139. @param comparator an object which defines a compareElements() method
  5140. @param array the array to search
  5141. @param newElement the value that is going to be inserted
  5142. @param firstElement the index of the first element to search
  5143. @param lastElement the index of the last element in the range (this is non-inclusive)
  5144. */
  5145. template <class ElementType, class ElementComparator>
  5146. static int findInsertIndexInSortedArray (ElementComparator& comparator,
  5147. ElementType* const array,
  5148. const ElementType newElement,
  5149. int firstElement,
  5150. int lastElement)
  5151. {
  5152. jassert (firstElement <= lastElement);
  5153. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5154. // avoids getting warning messages about the parameter being unused
  5155. while (firstElement < lastElement)
  5156. {
  5157. if (comparator.compareElements (newElement, array [firstElement]) == 0)
  5158. {
  5159. ++firstElement;
  5160. break;
  5161. }
  5162. else
  5163. {
  5164. const int halfway = (firstElement + lastElement) >> 1;
  5165. if (halfway == firstElement)
  5166. {
  5167. if (comparator.compareElements (newElement, array [halfway]) >= 0)
  5168. ++firstElement;
  5169. break;
  5170. }
  5171. else if (comparator.compareElements (newElement, array [halfway]) >= 0)
  5172. {
  5173. firstElement = halfway;
  5174. }
  5175. else
  5176. {
  5177. lastElement = halfway;
  5178. }
  5179. }
  5180. }
  5181. return firstElement;
  5182. }
  5183. /**
  5184. A simple ElementComparator class that can be used to sort an array of
  5185. objects that support the '<' operator.
  5186. This will work for primitive types and objects that implement operator<().
  5187. Example: @code
  5188. Array <int> myArray;
  5189. DefaultElementComparator<int> sorter;
  5190. myArray.sort (sorter);
  5191. @endcode
  5192. @see ElementComparator
  5193. */
  5194. template <class ElementType>
  5195. class DefaultElementComparator
  5196. {
  5197. private:
  5198. typedef PARAMETER_TYPE (ElementType) ParameterType;
  5199. public:
  5200. static int compareElements (ParameterType first, ParameterType second)
  5201. {
  5202. return (first < second) ? -1 : ((second < first) ? 1 : 0);
  5203. }
  5204. };
  5205. #endif // __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  5206. /*** End of inlined file: juce_ElementComparator.h ***/
  5207. /*** Start of inlined file: juce_CriticalSection.h ***/
  5208. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  5209. #define __JUCE_CRITICALSECTION_JUCEHEADER__
  5210. /*** Start of inlined file: juce_ScopedLock.h ***/
  5211. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  5212. #define __JUCE_SCOPEDLOCK_JUCEHEADER__
  5213. /**
  5214. Automatically locks and unlocks a mutex object.
  5215. Use one of these as a local variable to provide RAII-based locking of a mutex.
  5216. The templated class could be a CriticalSection, SpinLock, or anything else that
  5217. provides enter() and exit() methods.
  5218. e.g. @code
  5219. CriticalSection myCriticalSection;
  5220. for (;;)
  5221. {
  5222. const GenericScopedLock<CriticalSection> myScopedLock (myCriticalSection);
  5223. // myCriticalSection is now locked
  5224. ...do some stuff...
  5225. // myCriticalSection gets unlocked here.
  5226. }
  5227. @endcode
  5228. @see GenericScopedUnlock, CriticalSection, SpinLock, ScopedLock, ScopedUnlock
  5229. */
  5230. template <class LockType>
  5231. class GenericScopedLock
  5232. {
  5233. public:
  5234. /** Creates a GenericScopedLock.
  5235. As soon as it is created, this will acquire the lock, and when the GenericScopedLock
  5236. object is deleted, the lock will be released.
  5237. Make sure this object is created and deleted by the same thread,
  5238. otherwise there are no guarantees what will happen! Best just to use it
  5239. as a local stack object, rather than creating one with the new() operator.
  5240. */
  5241. inline explicit GenericScopedLock (const LockType& lock) noexcept : lock_ (lock) { lock.enter(); }
  5242. /** Destructor.
  5243. The lock will be released when the destructor is called.
  5244. Make sure this object is created and deleted by the same thread, otherwise there are
  5245. no guarantees what will happen!
  5246. */
  5247. inline ~GenericScopedLock() noexcept { lock_.exit(); }
  5248. private:
  5249. const LockType& lock_;
  5250. JUCE_DECLARE_NON_COPYABLE (GenericScopedLock);
  5251. };
  5252. /**
  5253. Automatically unlocks and re-locks a mutex object.
  5254. This is the reverse of a GenericScopedLock object - instead of locking the mutex
  5255. for the lifetime of this object, it unlocks it.
  5256. Make sure you don't try to unlock mutexes that aren't actually locked!
  5257. e.g. @code
  5258. CriticalSection myCriticalSection;
  5259. for (;;)
  5260. {
  5261. const GenericScopedLock<CriticalSection> myScopedLock (myCriticalSection);
  5262. // myCriticalSection is now locked
  5263. ... do some stuff with it locked ..
  5264. while (xyz)
  5265. {
  5266. ... do some stuff with it locked ..
  5267. const GenericScopedUnlock<CriticalSection> unlocker (myCriticalSection);
  5268. // myCriticalSection is now unlocked for the remainder of this block,
  5269. // and re-locked at the end.
  5270. ...do some stuff with it unlocked ...
  5271. }
  5272. // myCriticalSection gets unlocked here.
  5273. }
  5274. @endcode
  5275. @see GenericScopedLock, CriticalSection, ScopedLock, ScopedUnlock
  5276. */
  5277. template <class LockType>
  5278. class GenericScopedUnlock
  5279. {
  5280. public:
  5281. /** Creates a GenericScopedUnlock.
  5282. As soon as it is created, this will unlock the CriticalSection, and
  5283. when the ScopedLock object is deleted, the CriticalSection will
  5284. be re-locked.
  5285. Make sure this object is created and deleted by the same thread,
  5286. otherwise there are no guarantees what will happen! Best just to use it
  5287. as a local stack object, rather than creating one with the new() operator.
  5288. */
  5289. inline explicit GenericScopedUnlock (const LockType& lock) noexcept : lock_ (lock) { lock.exit(); }
  5290. /** Destructor.
  5291. The CriticalSection will be unlocked when the destructor is called.
  5292. Make sure this object is created and deleted by the same thread,
  5293. otherwise there are no guarantees what will happen!
  5294. */
  5295. inline ~GenericScopedUnlock() noexcept { lock_.enter(); }
  5296. private:
  5297. const LockType& lock_;
  5298. JUCE_DECLARE_NON_COPYABLE (GenericScopedUnlock);
  5299. };
  5300. /**
  5301. Automatically locks and unlocks a mutex object.
  5302. Use one of these as a local variable to provide RAII-based locking of a mutex.
  5303. The templated class could be a CriticalSection, SpinLock, or anything else that
  5304. provides enter() and exit() methods.
  5305. e.g. @code
  5306. CriticalSection myCriticalSection;
  5307. for (;;)
  5308. {
  5309. const GenericScopedTryLock<CriticalSection> myScopedTryLock (myCriticalSection);
  5310. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  5311. // should test this with the isLocked() method before doing your thread-unsafe
  5312. // action..
  5313. if (myScopedTryLock.isLocked())
  5314. {
  5315. ...do some stuff...
  5316. }
  5317. else
  5318. {
  5319. ..our attempt at locking failed because another thread had already locked it..
  5320. }
  5321. // myCriticalSection gets unlocked here (if it was locked)
  5322. }
  5323. @endcode
  5324. @see CriticalSection::tryEnter, GenericScopedLock, GenericScopedUnlock
  5325. */
  5326. template <class LockType>
  5327. class GenericScopedTryLock
  5328. {
  5329. public:
  5330. /** Creates a GenericScopedTryLock.
  5331. As soon as it is created, this will attempt to acquire the lock, and when the
  5332. GenericScopedTryLock is deleted, the lock will be released (if the lock was
  5333. successfully acquired).
  5334. Make sure this object is created and deleted by the same thread,
  5335. otherwise there are no guarantees what will happen! Best just to use it
  5336. as a local stack object, rather than creating one with the new() operator.
  5337. */
  5338. inline explicit GenericScopedTryLock (const LockType& lock) noexcept
  5339. : lock_ (lock), lockWasSuccessful (lock.tryEnter()) {}
  5340. /** Destructor.
  5341. The mutex will be unlocked (if it had been successfully locked) when the
  5342. destructor is called.
  5343. Make sure this object is created and deleted by the same thread,
  5344. otherwise there are no guarantees what will happen!
  5345. */
  5346. inline ~GenericScopedTryLock() noexcept { if (lockWasSuccessful) lock_.exit(); }
  5347. /** Returns true if the mutex was successfully locked. */
  5348. bool isLocked() const noexcept { return lockWasSuccessful; }
  5349. private:
  5350. const LockType& lock_;
  5351. const bool lockWasSuccessful;
  5352. JUCE_DECLARE_NON_COPYABLE (GenericScopedTryLock);
  5353. };
  5354. #endif // __JUCE_SCOPEDLOCK_JUCEHEADER__
  5355. /*** End of inlined file: juce_ScopedLock.h ***/
  5356. /**
  5357. A mutex class.
  5358. A CriticalSection acts as a re-entrant mutex lock. The best way to lock and unlock
  5359. one of these is by using RAII in the form of a local ScopedLock object - have a look
  5360. through the codebase for many examples of how to do this.
  5361. @see ScopedLock, ScopedTryLock, ScopedUnlock, SpinLock, ReadWriteLock, Thread, InterProcessLock
  5362. */
  5363. class JUCE_API CriticalSection
  5364. {
  5365. public:
  5366. /** Creates a CriticalSection object. */
  5367. CriticalSection() noexcept;
  5368. /** Destructor.
  5369. If the critical section is deleted whilst locked, any subsequent behaviour
  5370. is unpredictable.
  5371. */
  5372. ~CriticalSection() noexcept;
  5373. /** Acquires the lock.
  5374. If the lock is already held by the caller thread, the method returns immediately.
  5375. If the lock is currently held by another thread, this will wait until it becomes free.
  5376. It's strongly recommended that you never call this method directly - instead use the
  5377. ScopedLock class to manage the locking using an RAII pattern instead.
  5378. @see exit, tryEnter, ScopedLock
  5379. */
  5380. void enter() const noexcept;
  5381. /** Attempts to lock this critical section without blocking.
  5382. This method behaves identically to CriticalSection::enter, except that the caller thread
  5383. does not wait if the lock is currently held by another thread but returns false immediately.
  5384. @returns false if the lock is currently held by another thread, true otherwise.
  5385. @see enter
  5386. */
  5387. bool tryEnter() const noexcept;
  5388. /** Releases the lock.
  5389. If the caller thread hasn't got the lock, this can have unpredictable results.
  5390. If the enter() method has been called multiple times by the thread, each
  5391. call must be matched by a call to exit() before other threads will be allowed
  5392. to take over the lock.
  5393. @see enter, ScopedLock
  5394. */
  5395. void exit() const noexcept;
  5396. /** Provides the type of scoped lock to use with a CriticalSection. */
  5397. typedef GenericScopedLock <CriticalSection> ScopedLockType;
  5398. /** Provides the type of scoped unlocker to use with a CriticalSection. */
  5399. typedef GenericScopedUnlock <CriticalSection> ScopedUnlockType;
  5400. /** Provides the type of scoped try-locker to use with a CriticalSection. */
  5401. typedef GenericScopedTryLock <CriticalSection> ScopedTryLockType;
  5402. private:
  5403. #if JUCE_WINDOWS
  5404. // To avoid including windows.h in the public JUCE headers, we'll just allocate a
  5405. // block of memory here that's big enough to be used internally as a windows critical
  5406. // section structure.
  5407. #if JUCE_64BIT
  5408. uint8 internal [44];
  5409. #else
  5410. uint8 internal [24];
  5411. #endif
  5412. #else
  5413. mutable pthread_mutex_t internal;
  5414. #endif
  5415. JUCE_DECLARE_NON_COPYABLE (CriticalSection);
  5416. };
  5417. /**
  5418. A class that can be used in place of a real CriticalSection object, but which
  5419. doesn't perform any locking.
  5420. This is currently used by some templated classes, and most compilers should
  5421. manage to optimise it out of existence.
  5422. @see CriticalSection, Array, OwnedArray, ReferenceCountedArray
  5423. */
  5424. class JUCE_API DummyCriticalSection
  5425. {
  5426. public:
  5427. inline DummyCriticalSection() noexcept {}
  5428. inline ~DummyCriticalSection() noexcept {}
  5429. inline void enter() const noexcept {}
  5430. inline bool tryEnter() const noexcept { return true; }
  5431. inline void exit() const noexcept {}
  5432. /** A dummy scoped-lock type to use with a dummy critical section. */
  5433. struct ScopedLockType
  5434. {
  5435. ScopedLockType (const DummyCriticalSection&) noexcept {}
  5436. };
  5437. /** A dummy scoped-unlocker type to use with a dummy critical section. */
  5438. typedef ScopedLockType ScopedUnlockType;
  5439. private:
  5440. JUCE_DECLARE_NON_COPYABLE (DummyCriticalSection);
  5441. };
  5442. /**
  5443. Automatically locks and unlocks a CriticalSection object.
  5444. Use one of these as a local variable to provide RAII-based locking of a CriticalSection.
  5445. e.g. @code
  5446. CriticalSection myCriticalSection;
  5447. for (;;)
  5448. {
  5449. const ScopedLock myScopedLock (myCriticalSection);
  5450. // myCriticalSection is now locked
  5451. ...do some stuff...
  5452. // myCriticalSection gets unlocked here.
  5453. }
  5454. @endcode
  5455. @see CriticalSection, ScopedUnlock
  5456. */
  5457. typedef CriticalSection::ScopedLockType ScopedLock;
  5458. /**
  5459. Automatically unlocks and re-locks a CriticalSection object.
  5460. This is the reverse of a ScopedLock object - instead of locking the critical
  5461. section for the lifetime of this object, it unlocks it.
  5462. Make sure you don't try to unlock critical sections that aren't actually locked!
  5463. e.g. @code
  5464. CriticalSection myCriticalSection;
  5465. for (;;)
  5466. {
  5467. const ScopedLock myScopedLock (myCriticalSection);
  5468. // myCriticalSection is now locked
  5469. ... do some stuff with it locked ..
  5470. while (xyz)
  5471. {
  5472. ... do some stuff with it locked ..
  5473. const ScopedUnlock unlocker (myCriticalSection);
  5474. // myCriticalSection is now unlocked for the remainder of this block,
  5475. // and re-locked at the end.
  5476. ...do some stuff with it unlocked ...
  5477. }
  5478. // myCriticalSection gets unlocked here.
  5479. }
  5480. @endcode
  5481. @see CriticalSection, ScopedLock
  5482. */
  5483. typedef CriticalSection::ScopedUnlockType ScopedUnlock;
  5484. /**
  5485. Automatically tries to lock and unlock a CriticalSection object.
  5486. Use one of these as a local variable to control access to a CriticalSection.
  5487. e.g. @code
  5488. CriticalSection myCriticalSection;
  5489. for (;;)
  5490. {
  5491. const ScopedTryLock myScopedTryLock (myCriticalSection);
  5492. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  5493. // should test this with the isLocked() method before doing your thread-unsafe
  5494. // action..
  5495. if (myScopedTryLock.isLocked())
  5496. {
  5497. ...do some stuff...
  5498. }
  5499. else
  5500. {
  5501. ..our attempt at locking failed because another thread had already locked it..
  5502. }
  5503. // myCriticalSection gets unlocked here (if it was locked)
  5504. }
  5505. @endcode
  5506. @see CriticalSection::tryEnter, ScopedLock, ScopedUnlock, ScopedReadLock
  5507. */
  5508. typedef CriticalSection::ScopedTryLockType ScopedTryLock;
  5509. #endif // __JUCE_CRITICALSECTION_JUCEHEADER__
  5510. /*** End of inlined file: juce_CriticalSection.h ***/
  5511. /**
  5512. Holds a resizable array of primitive or copy-by-value objects.
  5513. Examples of arrays are: Array<int>, Array<Rectangle> or Array<MyClass*>
  5514. The Array class can be used to hold simple, non-polymorphic objects as well as primitive types - to
  5515. do so, the class must fulfil these requirements:
  5516. - it must have a copy constructor and assignment operator
  5517. - it must be able to be relocated in memory by a memcpy without this causing any problems - so
  5518. objects whose functionality relies on external pointers or references to themselves can be used.
  5519. You can of course have an array of pointers to any kind of object, e.g. Array <MyClass*>, but if
  5520. you do this, the array doesn't take any ownership of the objects - see the OwnedArray class or the
  5521. ReferenceCountedArray class for more powerful ways of holding lists of objects.
  5522. For holding lists of strings, you can use Array\<String\>, but it's usually better to use the
  5523. specialised class StringArray, which provides more useful functions.
  5524. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  5525. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  5526. @see OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  5527. */
  5528. template <typename ElementType,
  5529. typename TypeOfCriticalSectionToUse = DummyCriticalSection>
  5530. class Array
  5531. {
  5532. private:
  5533. typedef PARAMETER_TYPE (ElementType) ParameterType;
  5534. public:
  5535. /** Creates an empty array. */
  5536. Array() noexcept
  5537. : numUsed (0)
  5538. {
  5539. }
  5540. /** Creates a copy of another array.
  5541. @param other the array to copy
  5542. */
  5543. Array (const Array<ElementType, TypeOfCriticalSectionToUse>& other)
  5544. {
  5545. const ScopedLockType lock (other.getLock());
  5546. numUsed = other.numUsed;
  5547. data.setAllocatedSize (other.numUsed);
  5548. for (int i = 0; i < numUsed; ++i)
  5549. new (data.elements + i) ElementType (other.data.elements[i]);
  5550. }
  5551. /** Initalises from a null-terminated C array of values.
  5552. @param values the array to copy from
  5553. */
  5554. template <typename TypeToCreateFrom>
  5555. explicit Array (const TypeToCreateFrom* values)
  5556. : numUsed (0)
  5557. {
  5558. while (*values != TypeToCreateFrom())
  5559. add (*values++);
  5560. }
  5561. /** Initalises from a C array of values.
  5562. @param values the array to copy from
  5563. @param numValues the number of values in the array
  5564. */
  5565. template <typename TypeToCreateFrom>
  5566. Array (const TypeToCreateFrom* values, int numValues)
  5567. : numUsed (numValues)
  5568. {
  5569. data.setAllocatedSize (numValues);
  5570. for (int i = 0; i < numValues; ++i)
  5571. new (data.elements + i) ElementType (values[i]);
  5572. }
  5573. /** Destructor. */
  5574. ~Array()
  5575. {
  5576. for (int i = 0; i < numUsed; ++i)
  5577. data.elements[i].~ElementType();
  5578. }
  5579. /** Copies another array.
  5580. @param other the array to copy
  5581. */
  5582. Array& operator= (const Array& other)
  5583. {
  5584. if (this != &other)
  5585. {
  5586. Array<ElementType, TypeOfCriticalSectionToUse> otherCopy (other);
  5587. swapWithArray (otherCopy);
  5588. }
  5589. return *this;
  5590. }
  5591. /** Compares this array to another one.
  5592. Two arrays are considered equal if they both contain the same set of
  5593. elements, in the same order.
  5594. @param other the other array to compare with
  5595. */
  5596. template <class OtherArrayType>
  5597. bool operator== (const OtherArrayType& other) const
  5598. {
  5599. const ScopedLockType lock (getLock());
  5600. const typename OtherArrayType::ScopedLockType lock2 (other.getLock());
  5601. if (numUsed != other.numUsed)
  5602. return false;
  5603. for (int i = numUsed; --i >= 0;)
  5604. if (! (data.elements [i] == other.data.elements [i]))
  5605. return false;
  5606. return true;
  5607. }
  5608. /** Compares this array to another one.
  5609. Two arrays are considered equal if they both contain the same set of
  5610. elements, in the same order.
  5611. @param other the other array to compare with
  5612. */
  5613. template <class OtherArrayType>
  5614. bool operator!= (const OtherArrayType& other) const
  5615. {
  5616. return ! operator== (other);
  5617. }
  5618. /** Removes all elements from the array.
  5619. This will remove all the elements, and free any storage that the array is
  5620. using. To clear the array without freeing the storage, use the clearQuick()
  5621. method instead.
  5622. @see clearQuick
  5623. */
  5624. void clear()
  5625. {
  5626. const ScopedLockType lock (getLock());
  5627. for (int i = 0; i < numUsed; ++i)
  5628. data.elements[i].~ElementType();
  5629. data.setAllocatedSize (0);
  5630. numUsed = 0;
  5631. }
  5632. /** Removes all elements from the array without freeing the array's allocated storage.
  5633. @see clear
  5634. */
  5635. void clearQuick()
  5636. {
  5637. const ScopedLockType lock (getLock());
  5638. for (int i = 0; i < numUsed; ++i)
  5639. data.elements[i].~ElementType();
  5640. numUsed = 0;
  5641. }
  5642. /** Returns the current number of elements in the array.
  5643. */
  5644. inline int size() const noexcept
  5645. {
  5646. return numUsed;
  5647. }
  5648. /** Returns one of the elements in the array.
  5649. If the index passed in is beyond the range of valid elements, this
  5650. will return zero.
  5651. If you're certain that the index will always be a valid element, you
  5652. can call getUnchecked() instead, which is faster.
  5653. @param index the index of the element being requested (0 is the first element in the array)
  5654. @see getUnchecked, getFirst, getLast
  5655. */
  5656. const ElementType operator[] (const int index) const
  5657. {
  5658. const ScopedLockType lock (getLock());
  5659. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  5660. : ElementType();
  5661. }
  5662. /** Returns one of the elements in the array, without checking the index passed in.
  5663. Unlike the operator[] method, this will try to return an element without
  5664. checking that the index is within the bounds of the array, so should only
  5665. be used when you're confident that it will always be a valid index.
  5666. @param index the index of the element being requested (0 is the first element in the array)
  5667. @see operator[], getFirst, getLast
  5668. */
  5669. inline const ElementType getUnchecked (const int index) const
  5670. {
  5671. const ScopedLockType lock (getLock());
  5672. jassert (isPositiveAndBelow (index, numUsed));
  5673. return data.elements [index];
  5674. }
  5675. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  5676. This is like getUnchecked, but returns a direct reference to the element, so that
  5677. you can alter it directly. Obviously this can be dangerous, so only use it when
  5678. absolutely necessary.
  5679. @param index the index of the element being requested (0 is the first element in the array)
  5680. @see operator[], getFirst, getLast
  5681. */
  5682. inline ElementType& getReference (const int index) const noexcept
  5683. {
  5684. const ScopedLockType lock (getLock());
  5685. jassert (isPositiveAndBelow (index, numUsed));
  5686. return data.elements [index];
  5687. }
  5688. /** Returns the first element in the array, or 0 if the array is empty.
  5689. @see operator[], getUnchecked, getLast
  5690. */
  5691. inline ElementType getFirst() const
  5692. {
  5693. const ScopedLockType lock (getLock());
  5694. return (numUsed > 0) ? data.elements [0]
  5695. : ElementType();
  5696. }
  5697. /** Returns the last element in the array, or 0 if the array is empty.
  5698. @see operator[], getUnchecked, getFirst
  5699. */
  5700. inline ElementType getLast() const
  5701. {
  5702. const ScopedLockType lock (getLock());
  5703. return (numUsed > 0) ? data.elements [numUsed - 1]
  5704. : ElementType();
  5705. }
  5706. /** Returns a pointer to the actual array data.
  5707. This pointer will only be valid until the next time a non-const method
  5708. is called on the array.
  5709. */
  5710. inline ElementType* getRawDataPointer() noexcept
  5711. {
  5712. return data.elements;
  5713. }
  5714. /** Returns a pointer to the first element in the array.
  5715. This method is provided for compatibility with standard C++ iteration mechanisms.
  5716. */
  5717. inline ElementType* begin() const noexcept
  5718. {
  5719. return data.elements;
  5720. }
  5721. /** Returns a pointer to the element which follows the last element in the array.
  5722. This method is provided for compatibility with standard C++ iteration mechanisms.
  5723. */
  5724. inline ElementType* end() const noexcept
  5725. {
  5726. return data.elements + numUsed;
  5727. }
  5728. /** Finds the index of the first element which matches the value passed in.
  5729. This will search the array for the given object, and return the index
  5730. of its first occurrence. If the object isn't found, the method will return -1.
  5731. @param elementToLookFor the value or object to look for
  5732. @returns the index of the object, or -1 if it's not found
  5733. */
  5734. int indexOf (ParameterType elementToLookFor) const
  5735. {
  5736. const ScopedLockType lock (getLock());
  5737. const ElementType* e = data.elements.getData();
  5738. const ElementType* const end_ = e + numUsed;
  5739. for (; e != end_; ++e)
  5740. if (elementToLookFor == *e)
  5741. return static_cast <int> (e - data.elements.getData());
  5742. return -1;
  5743. }
  5744. /** Returns true if the array contains at least one occurrence of an object.
  5745. @param elementToLookFor the value or object to look for
  5746. @returns true if the item is found
  5747. */
  5748. bool contains (ParameterType elementToLookFor) const
  5749. {
  5750. const ScopedLockType lock (getLock());
  5751. const ElementType* e = data.elements.getData();
  5752. const ElementType* const end_ = e + numUsed;
  5753. for (; e != end_; ++e)
  5754. if (elementToLookFor == *e)
  5755. return true;
  5756. return false;
  5757. }
  5758. /** Appends a new element at the end of the array.
  5759. @param newElement the new object to add to the array
  5760. @see set, insert, addIfNotAlreadyThere, addSorted, addUsingDefaultSort, addArray
  5761. */
  5762. void add (ParameterType newElement)
  5763. {
  5764. const ScopedLockType lock (getLock());
  5765. data.ensureAllocatedSize (numUsed + 1);
  5766. new (data.elements + numUsed++) ElementType (newElement);
  5767. }
  5768. /** Inserts a new element into the array at a given position.
  5769. If the index is less than 0 or greater than the size of the array, the
  5770. element will be added to the end of the array.
  5771. Otherwise, it will be inserted into the array, moving all the later elements
  5772. along to make room.
  5773. @param indexToInsertAt the index at which the new element should be
  5774. inserted (pass in -1 to add it to the end)
  5775. @param newElement the new object to add to the array
  5776. @see add, addSorted, addUsingDefaultSort, set
  5777. */
  5778. void insert (int indexToInsertAt, ParameterType newElement)
  5779. {
  5780. const ScopedLockType lock (getLock());
  5781. data.ensureAllocatedSize (numUsed + 1);
  5782. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  5783. {
  5784. ElementType* const insertPos = data.elements + indexToInsertAt;
  5785. const int numberToMove = numUsed - indexToInsertAt;
  5786. if (numberToMove > 0)
  5787. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  5788. new (insertPos) ElementType (newElement);
  5789. ++numUsed;
  5790. }
  5791. else
  5792. {
  5793. new (data.elements + numUsed++) ElementType (newElement);
  5794. }
  5795. }
  5796. /** Inserts multiple copies of an element into the array at a given position.
  5797. If the index is less than 0 or greater than the size of the array, the
  5798. element will be added to the end of the array.
  5799. Otherwise, it will be inserted into the array, moving all the later elements
  5800. along to make room.
  5801. @param indexToInsertAt the index at which the new element should be inserted
  5802. @param newElement the new object to add to the array
  5803. @param numberOfTimesToInsertIt how many copies of the value to insert
  5804. @see insert, add, addSorted, set
  5805. */
  5806. void insertMultiple (int indexToInsertAt, ParameterType newElement,
  5807. int numberOfTimesToInsertIt)
  5808. {
  5809. if (numberOfTimesToInsertIt > 0)
  5810. {
  5811. const ScopedLockType lock (getLock());
  5812. data.ensureAllocatedSize (numUsed + numberOfTimesToInsertIt);
  5813. ElementType* insertPos;
  5814. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  5815. {
  5816. insertPos = data.elements + indexToInsertAt;
  5817. const int numberToMove = numUsed - indexToInsertAt;
  5818. memmove (insertPos + numberOfTimesToInsertIt, insertPos, numberToMove * sizeof (ElementType));
  5819. }
  5820. else
  5821. {
  5822. insertPos = data.elements + numUsed;
  5823. }
  5824. numUsed += numberOfTimesToInsertIt;
  5825. while (--numberOfTimesToInsertIt >= 0)
  5826. new (insertPos++) ElementType (newElement);
  5827. }
  5828. }
  5829. /** Inserts an array of values into this array at a given position.
  5830. If the index is less than 0 or greater than the size of the array, the
  5831. new elements will be added to the end of the array.
  5832. Otherwise, they will be inserted into the array, moving all the later elements
  5833. along to make room.
  5834. @param indexToInsertAt the index at which the first new element should be inserted
  5835. @param newElements the new values to add to the array
  5836. @param numberOfElements how many items are in the array
  5837. @see insert, add, addSorted, set
  5838. */
  5839. void insertArray (int indexToInsertAt,
  5840. const ElementType* newElements,
  5841. int numberOfElements)
  5842. {
  5843. if (numberOfElements > 0)
  5844. {
  5845. const ScopedLockType lock (getLock());
  5846. data.ensureAllocatedSize (numUsed + numberOfElements);
  5847. ElementType* insertPos;
  5848. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  5849. {
  5850. insertPos = data.elements + indexToInsertAt;
  5851. const int numberToMove = numUsed - indexToInsertAt;
  5852. memmove (insertPos + numberOfElements, insertPos, numberToMove * sizeof (ElementType));
  5853. }
  5854. else
  5855. {
  5856. insertPos = data.elements + numUsed;
  5857. }
  5858. numUsed += numberOfElements;
  5859. while (--numberOfElements >= 0)
  5860. new (insertPos++) ElementType (*newElements++);
  5861. }
  5862. }
  5863. /** Appends a new element at the end of the array as long as the array doesn't
  5864. already contain it.
  5865. If the array already contains an element that matches the one passed in, nothing
  5866. will be done.
  5867. @param newElement the new object to add to the array
  5868. */
  5869. void addIfNotAlreadyThere (ParameterType newElement)
  5870. {
  5871. const ScopedLockType lock (getLock());
  5872. if (! contains (newElement))
  5873. add (newElement);
  5874. }
  5875. /** Replaces an element with a new value.
  5876. If the index is less than zero, this method does nothing.
  5877. If the index is beyond the end of the array, the item is added to the end of the array.
  5878. @param indexToChange the index whose value you want to change
  5879. @param newValue the new value to set for this index.
  5880. @see add, insert
  5881. */
  5882. void set (const int indexToChange, ParameterType newValue)
  5883. {
  5884. jassert (indexToChange >= 0);
  5885. const ScopedLockType lock (getLock());
  5886. if (isPositiveAndBelow (indexToChange, numUsed))
  5887. {
  5888. data.elements [indexToChange] = newValue;
  5889. }
  5890. else if (indexToChange >= 0)
  5891. {
  5892. data.ensureAllocatedSize (numUsed + 1);
  5893. new (data.elements + numUsed++) ElementType (newValue);
  5894. }
  5895. }
  5896. /** Replaces an element with a new value without doing any bounds-checking.
  5897. This just sets a value directly in the array's internal storage, so you'd
  5898. better make sure it's in range!
  5899. @param indexToChange the index whose value you want to change
  5900. @param newValue the new value to set for this index.
  5901. @see set, getUnchecked
  5902. */
  5903. void setUnchecked (const int indexToChange, ParameterType newValue)
  5904. {
  5905. const ScopedLockType lock (getLock());
  5906. jassert (isPositiveAndBelow (indexToChange, numUsed));
  5907. data.elements [indexToChange] = newValue;
  5908. }
  5909. /** Adds elements from an array to the end of this array.
  5910. @param elementsToAdd the array of elements to add
  5911. @param numElementsToAdd how many elements are in this other array
  5912. @see add
  5913. */
  5914. void addArray (const ElementType* elementsToAdd, int numElementsToAdd)
  5915. {
  5916. const ScopedLockType lock (getLock());
  5917. if (numElementsToAdd > 0)
  5918. {
  5919. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  5920. while (--numElementsToAdd >= 0)
  5921. {
  5922. new (data.elements + numUsed) ElementType (*elementsToAdd++);
  5923. ++numUsed;
  5924. }
  5925. }
  5926. }
  5927. /** This swaps the contents of this array with those of another array.
  5928. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  5929. because it just swaps their internal pointers.
  5930. */
  5931. void swapWithArray (Array& otherArray) noexcept
  5932. {
  5933. const ScopedLockType lock1 (getLock());
  5934. const ScopedLockType lock2 (otherArray.getLock());
  5935. data.swapWith (otherArray.data);
  5936. swapVariables (numUsed, otherArray.numUsed);
  5937. }
  5938. /** Adds elements from another array to the end of this array.
  5939. @param arrayToAddFrom the array from which to copy the elements
  5940. @param startIndex the first element of the other array to start copying from
  5941. @param numElementsToAdd how many elements to add from the other array. If this
  5942. value is negative or greater than the number of available elements,
  5943. all available elements will be copied.
  5944. @see add
  5945. */
  5946. template <class OtherArrayType>
  5947. void addArray (const OtherArrayType& arrayToAddFrom,
  5948. int startIndex = 0,
  5949. int numElementsToAdd = -1)
  5950. {
  5951. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  5952. {
  5953. const ScopedLockType lock2 (getLock());
  5954. if (startIndex < 0)
  5955. {
  5956. jassertfalse;
  5957. startIndex = 0;
  5958. }
  5959. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  5960. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  5961. while (--numElementsToAdd >= 0)
  5962. add (arrayToAddFrom.getUnchecked (startIndex++));
  5963. }
  5964. }
  5965. /** This will enlarge or shrink the array to the given number of elements, by adding
  5966. or removing items from its end.
  5967. If the array is smaller than the given target size, empty elements will be appended
  5968. until its size is as specified. If its size is larger than the target, items will be
  5969. removed from its end to shorten it.
  5970. */
  5971. void resize (const int targetNumItems)
  5972. {
  5973. jassert (targetNumItems >= 0);
  5974. const int numToAdd = targetNumItems - numUsed;
  5975. if (numToAdd > 0)
  5976. insertMultiple (numUsed, ElementType(), numToAdd);
  5977. else if (numToAdd < 0)
  5978. removeRange (targetNumItems, -numToAdd);
  5979. }
  5980. /** Inserts a new element into the array, assuming that the array is sorted.
  5981. This will use a comparator to find the position at which the new element
  5982. should go. If the array isn't sorted, the behaviour of this
  5983. method will be unpredictable.
  5984. @param comparator the comparator to use to compare the elements - see the sort()
  5985. method for details about the form this object should take
  5986. @param newElement the new element to insert to the array
  5987. @returns the index at which the new item was added
  5988. @see addUsingDefaultSort, add, sort
  5989. */
  5990. template <class ElementComparator>
  5991. int addSorted (ElementComparator& comparator, ParameterType newElement)
  5992. {
  5993. const ScopedLockType lock (getLock());
  5994. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newElement, 0, numUsed);
  5995. insert (index, newElement);
  5996. return index;
  5997. }
  5998. /** Inserts a new element into the array, assuming that the array is sorted.
  5999. This will use the DefaultElementComparator class for sorting, so your ElementType
  6000. must be suitable for use with that class. If the array isn't sorted, the behaviour of this
  6001. method will be unpredictable.
  6002. @param newElement the new element to insert to the array
  6003. @see addSorted, sort
  6004. */
  6005. void addUsingDefaultSort (ParameterType newElement)
  6006. {
  6007. DefaultElementComparator <ElementType> comparator;
  6008. addSorted (comparator, newElement);
  6009. }
  6010. /** Finds the index of an element in the array, assuming that the array is sorted.
  6011. This will use a comparator to do a binary-chop to find the index of the given
  6012. element, if it exists. If the array isn't sorted, the behaviour of this
  6013. method will be unpredictable.
  6014. @param comparator the comparator to use to compare the elements - see the sort()
  6015. method for details about the form this object should take
  6016. @param elementToLookFor the element to search for
  6017. @returns the index of the element, or -1 if it's not found
  6018. @see addSorted, sort
  6019. */
  6020. template <class ElementComparator>
  6021. int indexOfSorted (ElementComparator& comparator, ParameterType elementToLookFor) const
  6022. {
  6023. (void) comparator; // if you pass in an object with a static compareElements() method, this
  6024. // avoids getting warning messages about the parameter being unused
  6025. const ScopedLockType lock (getLock());
  6026. int start = 0;
  6027. int end_ = numUsed;
  6028. for (;;)
  6029. {
  6030. if (start >= end_)
  6031. {
  6032. return -1;
  6033. }
  6034. else if (comparator.compareElements (elementToLookFor, data.elements [start]) == 0)
  6035. {
  6036. return start;
  6037. }
  6038. else
  6039. {
  6040. const int halfway = (start + end_) >> 1;
  6041. if (halfway == start)
  6042. return -1;
  6043. else if (comparator.compareElements (elementToLookFor, data.elements [halfway]) >= 0)
  6044. start = halfway;
  6045. else
  6046. end_ = halfway;
  6047. }
  6048. }
  6049. }
  6050. /** Removes an element from the array.
  6051. This will remove the element at a given index, and move back
  6052. all the subsequent elements to close the gap.
  6053. If the index passed in is out-of-range, nothing will happen.
  6054. @param indexToRemove the index of the element to remove
  6055. @returns the element that has been removed
  6056. @see removeValue, removeRange
  6057. */
  6058. ElementType remove (const int indexToRemove)
  6059. {
  6060. const ScopedLockType lock (getLock());
  6061. if (isPositiveAndBelow (indexToRemove, numUsed))
  6062. {
  6063. --numUsed;
  6064. ElementType* const e = data.elements + indexToRemove;
  6065. ElementType removed (*e);
  6066. e->~ElementType();
  6067. const int numberToShift = numUsed - indexToRemove;
  6068. if (numberToShift > 0)
  6069. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  6070. if ((numUsed << 1) < data.numAllocated)
  6071. minimiseStorageOverheads();
  6072. return removed;
  6073. }
  6074. else
  6075. {
  6076. return ElementType();
  6077. }
  6078. }
  6079. /** Removes an item from the array.
  6080. This will remove the first occurrence of the given element from the array.
  6081. If the item isn't found, no action is taken.
  6082. @param valueToRemove the object to try to remove
  6083. @see remove, removeRange
  6084. */
  6085. void removeValue (ParameterType valueToRemove)
  6086. {
  6087. const ScopedLockType lock (getLock());
  6088. ElementType* const e = data.elements;
  6089. for (int i = 0; i < numUsed; ++i)
  6090. {
  6091. if (valueToRemove == e[i])
  6092. {
  6093. remove (i);
  6094. break;
  6095. }
  6096. }
  6097. }
  6098. /** Removes a range of elements from the array.
  6099. This will remove a set of elements, starting from the given index,
  6100. and move subsequent elements down to close the gap.
  6101. If the range extends beyond the bounds of the array, it will
  6102. be safely clipped to the size of the array.
  6103. @param startIndex the index of the first element to remove
  6104. @param numberToRemove how many elements should be removed
  6105. @see remove, removeValue
  6106. */
  6107. void removeRange (int startIndex, int numberToRemove)
  6108. {
  6109. const ScopedLockType lock (getLock());
  6110. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  6111. startIndex = jlimit (0, numUsed, startIndex);
  6112. if (endIndex > startIndex)
  6113. {
  6114. ElementType* const e = data.elements + startIndex;
  6115. numberToRemove = endIndex - startIndex;
  6116. for (int i = 0; i < numberToRemove; ++i)
  6117. e[i].~ElementType();
  6118. const int numToShift = numUsed - endIndex;
  6119. if (numToShift > 0)
  6120. memmove (e, e + numberToRemove, numToShift * sizeof (ElementType));
  6121. numUsed -= numberToRemove;
  6122. if ((numUsed << 1) < data.numAllocated)
  6123. minimiseStorageOverheads();
  6124. }
  6125. }
  6126. /** Removes the last n elements from the array.
  6127. @param howManyToRemove how many elements to remove from the end of the array
  6128. @see remove, removeValue, removeRange
  6129. */
  6130. void removeLast (int howManyToRemove = 1)
  6131. {
  6132. const ScopedLockType lock (getLock());
  6133. if (howManyToRemove > numUsed)
  6134. howManyToRemove = numUsed;
  6135. for (int i = 1; i <= howManyToRemove; ++i)
  6136. data.elements [numUsed - i].~ElementType();
  6137. numUsed -= howManyToRemove;
  6138. if ((numUsed << 1) < data.numAllocated)
  6139. minimiseStorageOverheads();
  6140. }
  6141. /** Removes any elements which are also in another array.
  6142. @param otherArray the other array in which to look for elements to remove
  6143. @see removeValuesNotIn, remove, removeValue, removeRange
  6144. */
  6145. template <class OtherArrayType>
  6146. void removeValuesIn (const OtherArrayType& otherArray)
  6147. {
  6148. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  6149. const ScopedLockType lock2 (getLock());
  6150. if (this == &otherArray)
  6151. {
  6152. clear();
  6153. }
  6154. else
  6155. {
  6156. if (otherArray.size() > 0)
  6157. {
  6158. for (int i = numUsed; --i >= 0;)
  6159. if (otherArray.contains (data.elements [i]))
  6160. remove (i);
  6161. }
  6162. }
  6163. }
  6164. /** Removes any elements which are not found in another array.
  6165. Only elements which occur in this other array will be retained.
  6166. @param otherArray the array in which to look for elements NOT to remove
  6167. @see removeValuesIn, remove, removeValue, removeRange
  6168. */
  6169. template <class OtherArrayType>
  6170. void removeValuesNotIn (const OtherArrayType& otherArray)
  6171. {
  6172. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  6173. const ScopedLockType lock2 (getLock());
  6174. if (this != &otherArray)
  6175. {
  6176. if (otherArray.size() <= 0)
  6177. {
  6178. clear();
  6179. }
  6180. else
  6181. {
  6182. for (int i = numUsed; --i >= 0;)
  6183. if (! otherArray.contains (data.elements [i]))
  6184. remove (i);
  6185. }
  6186. }
  6187. }
  6188. /** Swaps over two elements in the array.
  6189. This swaps over the elements found at the two indexes passed in.
  6190. If either index is out-of-range, this method will do nothing.
  6191. @param index1 index of one of the elements to swap
  6192. @param index2 index of the other element to swap
  6193. */
  6194. void swap (const int index1,
  6195. const int index2)
  6196. {
  6197. const ScopedLockType lock (getLock());
  6198. if (isPositiveAndBelow (index1, numUsed)
  6199. && isPositiveAndBelow (index2, numUsed))
  6200. {
  6201. swapVariables (data.elements [index1],
  6202. data.elements [index2]);
  6203. }
  6204. }
  6205. /** Moves one of the values to a different position.
  6206. This will move the value to a specified index, shuffling along
  6207. any intervening elements as required.
  6208. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  6209. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  6210. @param currentIndex the index of the value to be moved. If this isn't a
  6211. valid index, then nothing will be done
  6212. @param newIndex the index at which you'd like this value to end up. If this
  6213. is less than zero, the value will be moved to the end
  6214. of the array
  6215. */
  6216. void move (const int currentIndex, int newIndex) noexcept
  6217. {
  6218. if (currentIndex != newIndex)
  6219. {
  6220. const ScopedLockType lock (getLock());
  6221. if (isPositiveAndBelow (currentIndex, numUsed))
  6222. {
  6223. if (! isPositiveAndBelow (newIndex, numUsed))
  6224. newIndex = numUsed - 1;
  6225. char tempCopy [sizeof (ElementType)];
  6226. memcpy (tempCopy, data.elements + currentIndex, sizeof (ElementType));
  6227. if (newIndex > currentIndex)
  6228. {
  6229. memmove (data.elements + currentIndex,
  6230. data.elements + currentIndex + 1,
  6231. (newIndex - currentIndex) * sizeof (ElementType));
  6232. }
  6233. else
  6234. {
  6235. memmove (data.elements + newIndex + 1,
  6236. data.elements + newIndex,
  6237. (currentIndex - newIndex) * sizeof (ElementType));
  6238. }
  6239. memcpy (data.elements + newIndex, tempCopy, sizeof (ElementType));
  6240. }
  6241. }
  6242. }
  6243. /** Reduces the amount of storage being used by the array.
  6244. Arrays typically allocate slightly more storage than they need, and after
  6245. removing elements, they may have quite a lot of unused space allocated.
  6246. This method will reduce the amount of allocated storage to a minimum.
  6247. */
  6248. void minimiseStorageOverheads()
  6249. {
  6250. const ScopedLockType lock (getLock());
  6251. data.shrinkToNoMoreThan (numUsed);
  6252. }
  6253. /** Increases the array's internal storage to hold a minimum number of elements.
  6254. Calling this before adding a large known number of elements means that
  6255. the array won't have to keep dynamically resizing itself as the elements
  6256. are added, and it'll therefore be more efficient.
  6257. */
  6258. void ensureStorageAllocated (const int minNumElements)
  6259. {
  6260. const ScopedLockType lock (getLock());
  6261. data.ensureAllocatedSize (minNumElements);
  6262. }
  6263. /** Sorts the elements in the array.
  6264. This will use a comparator object to sort the elements into order. The object
  6265. passed must have a method of the form:
  6266. @code
  6267. int compareElements (ElementType first, ElementType second);
  6268. @endcode
  6269. ..and this method must return:
  6270. - a value of < 0 if the first comes before the second
  6271. - a value of 0 if the two objects are equivalent
  6272. - a value of > 0 if the second comes before the first
  6273. To improve performance, the compareElements() method can be declared as static or const.
  6274. @param comparator the comparator to use for comparing elements.
  6275. @param retainOrderOfEquivalentItems if this is true, then items
  6276. which the comparator says are equivalent will be
  6277. kept in the order in which they currently appear
  6278. in the array. This is slower to perform, but may
  6279. be important in some cases. If it's false, a faster
  6280. algorithm is used, but equivalent elements may be
  6281. rearranged.
  6282. @see addSorted, indexOfSorted, sortArray
  6283. */
  6284. template <class ElementComparator>
  6285. void sort (ElementComparator& comparator,
  6286. const bool retainOrderOfEquivalentItems = false) const
  6287. {
  6288. const ScopedLockType lock (getLock());
  6289. (void) comparator; // if you pass in an object with a static compareElements() method, this
  6290. // avoids getting warning messages about the parameter being unused
  6291. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  6292. }
  6293. /** Returns the CriticalSection that locks this array.
  6294. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  6295. an object of ScopedLockType as an RAII lock for it.
  6296. */
  6297. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return data; }
  6298. /** Returns the type of scoped lock to use for locking this array */
  6299. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  6300. private:
  6301. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  6302. int numUsed;
  6303. };
  6304. #endif // __JUCE_ARRAY_JUCEHEADER__
  6305. /*** End of inlined file: juce_Array.h ***/
  6306. #endif
  6307. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  6308. #endif
  6309. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  6310. /*** Start of inlined file: juce_DynamicObject.h ***/
  6311. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  6312. #define __JUCE_DYNAMICOBJECT_JUCEHEADER__
  6313. /*** Start of inlined file: juce_NamedValueSet.h ***/
  6314. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  6315. #define __JUCE_NAMEDVALUESET_JUCEHEADER__
  6316. /*** Start of inlined file: juce_Variant.h ***/
  6317. #ifndef __JUCE_VARIANT_JUCEHEADER__
  6318. #define __JUCE_VARIANT_JUCEHEADER__
  6319. /*** Start of inlined file: juce_Identifier.h ***/
  6320. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  6321. #define __JUCE_IDENTIFIER_JUCEHEADER__
  6322. class StringPool;
  6323. /**
  6324. Represents a string identifier, designed for accessing properties by name.
  6325. Identifier objects are very light and fast to copy, but slower to initialise
  6326. from a string, so it's much faster to keep a static identifier object to refer
  6327. to frequently-used names, rather than constructing them each time you need it.
  6328. @see NamedPropertySet, ValueTree
  6329. */
  6330. class JUCE_API Identifier
  6331. {
  6332. public:
  6333. /** Creates a null identifier. */
  6334. Identifier() noexcept;
  6335. /** Creates an identifier with a specified name.
  6336. Because this name may need to be used in contexts such as script variables or XML
  6337. tags, it must only contain ascii letters and digits, or the underscore character.
  6338. */
  6339. Identifier (const char* name);
  6340. /** Creates an identifier with a specified name.
  6341. Because this name may need to be used in contexts such as script variables or XML
  6342. tags, it must only contain ascii letters and digits, or the underscore character.
  6343. */
  6344. Identifier (const String& name);
  6345. /** Creates a copy of another identifier. */
  6346. Identifier (const Identifier& other) noexcept;
  6347. /** Creates a copy of another identifier. */
  6348. Identifier& operator= (const Identifier& other) noexcept;
  6349. /** Destructor */
  6350. ~Identifier();
  6351. /** Compares two identifiers. This is a very fast operation. */
  6352. inline bool operator== (const Identifier& other) const noexcept { return name == other.name; }
  6353. /** Compares two identifiers. This is a very fast operation. */
  6354. inline bool operator!= (const Identifier& other) const noexcept { return name != other.name; }
  6355. /** Returns this identifier as a string. */
  6356. String toString() const { return name; }
  6357. /** Returns this identifier's raw string pointer. */
  6358. operator const String::CharPointerType() const noexcept { return name; }
  6359. /** Checks a given string for characters that might not be valid in an Identifier.
  6360. Since Identifiers are used as a script variables and XML attributes, they should only contain
  6361. alphanumeric characters, underscores, or the '-' and ':' characters.
  6362. */
  6363. static bool isValidIdentifier (const String& possibleIdentifier) noexcept;
  6364. private:
  6365. String::CharPointerType name;
  6366. static StringPool& getPool();
  6367. };
  6368. #endif // __JUCE_IDENTIFIER_JUCEHEADER__
  6369. /*** End of inlined file: juce_Identifier.h ***/
  6370. /*** Start of inlined file: juce_OutputStream.h ***/
  6371. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6372. #define __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6373. /*** Start of inlined file: juce_NewLine.h ***/
  6374. #ifndef __JUCE_NEWLINE_JUCEHEADER__
  6375. #define __JUCE_NEWLINE_JUCEHEADER__
  6376. /** This class is used for represent a new-line character sequence.
  6377. To write a new-line to a stream, you can use the predefined 'newLine' variable, e.g.
  6378. @code
  6379. myOutputStream << "Hello World" << newLine << newLine;
  6380. @endcode
  6381. The exact character sequence that will be used for the new-line can be set and
  6382. retrieved with OutputStream::setNewLineString() and OutputStream::getNewLineString().
  6383. */
  6384. class JUCE_API NewLine
  6385. {
  6386. public:
  6387. /** Returns the default new-line sequence that the library uses.
  6388. @see OutputStream::setNewLineString()
  6389. */
  6390. static const char* getDefault() noexcept { return "\r\n"; }
  6391. /** Returns the default new-line sequence that the library uses.
  6392. @see getDefault()
  6393. */
  6394. operator String() const { return getDefault(); }
  6395. };
  6396. /** A predefined object representing a new-line, which can be written to a string or stream.
  6397. To write a new-line to a stream, you can use the predefined 'newLine' variable like this:
  6398. @code
  6399. myOutputStream << "Hello World" << newLine << newLine;
  6400. @endcode
  6401. */
  6402. extern NewLine newLine;
  6403. /** Writes a new-line sequence to a string.
  6404. You can use the predefined object 'newLine' to invoke this, e.g.
  6405. @code
  6406. myString << "Hello World" << newLine << newLine;
  6407. @endcode
  6408. */
  6409. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const NewLine&);
  6410. #endif // __JUCE_NEWLINE_JUCEHEADER__
  6411. /*** End of inlined file: juce_NewLine.h ***/
  6412. class InputStream;
  6413. class MemoryBlock;
  6414. class File;
  6415. /**
  6416. The base class for streams that write data to some kind of destination.
  6417. Input and output streams are used throughout the library - subclasses can override
  6418. some or all of the virtual functions to implement their behaviour.
  6419. @see InputStream, MemoryOutputStream, FileOutputStream
  6420. */
  6421. class JUCE_API OutputStream
  6422. {
  6423. protected:
  6424. OutputStream();
  6425. public:
  6426. /** Destructor.
  6427. Some subclasses might want to do things like call flush() during their
  6428. destructors.
  6429. */
  6430. virtual ~OutputStream();
  6431. /** If the stream is using a buffer, this will ensure it gets written
  6432. out to the destination. */
  6433. virtual void flush() = 0;
  6434. /** Tries to move the stream's output position.
  6435. Not all streams will be able to seek to a new position - this will return
  6436. false if it fails to work.
  6437. @see getPosition
  6438. */
  6439. virtual bool setPosition (int64 newPosition) = 0;
  6440. /** Returns the stream's current position.
  6441. @see setPosition
  6442. */
  6443. virtual int64 getPosition() = 0;
  6444. /** Writes a block of data to the stream.
  6445. When creating a subclass of OutputStream, this is the only write method
  6446. that needs to be overloaded - the base class has methods for writing other
  6447. types of data which use this to do the work.
  6448. @returns false if the write operation fails for some reason
  6449. */
  6450. virtual bool write (const void* dataToWrite,
  6451. int howManyBytes) = 0;
  6452. /** Writes a single byte to the stream.
  6453. @see InputStream::readByte
  6454. */
  6455. virtual void writeByte (char byte);
  6456. /** Writes a boolean to the stream as a single byte.
  6457. This is encoded as a binary byte (not as text) with a value of 1 or 0.
  6458. @see InputStream::readBool
  6459. */
  6460. virtual void writeBool (bool boolValue);
  6461. /** Writes a 16-bit integer to the stream in a little-endian byte order.
  6462. This will write two bytes to the stream: (value & 0xff), then (value >> 8).
  6463. @see InputStream::readShort
  6464. */
  6465. virtual void writeShort (short value);
  6466. /** Writes a 16-bit integer to the stream in a big-endian byte order.
  6467. This will write two bytes to the stream: (value >> 8), then (value & 0xff).
  6468. @see InputStream::readShortBigEndian
  6469. */
  6470. virtual void writeShortBigEndian (short value);
  6471. /** Writes a 32-bit integer to the stream in a little-endian byte order.
  6472. @see InputStream::readInt
  6473. */
  6474. virtual void writeInt (int value);
  6475. /** Writes a 32-bit integer to the stream in a big-endian byte order.
  6476. @see InputStream::readIntBigEndian
  6477. */
  6478. virtual void writeIntBigEndian (int value);
  6479. /** Writes a 64-bit integer to the stream in a little-endian byte order.
  6480. @see InputStream::readInt64
  6481. */
  6482. virtual void writeInt64 (int64 value);
  6483. /** Writes a 64-bit integer to the stream in a big-endian byte order.
  6484. @see InputStream::readInt64BigEndian
  6485. */
  6486. virtual void writeInt64BigEndian (int64 value);
  6487. /** Writes a 32-bit floating point value to the stream in a binary format.
  6488. The binary 32-bit encoding of the float is written as a little-endian int.
  6489. @see InputStream::readFloat
  6490. */
  6491. virtual void writeFloat (float value);
  6492. /** Writes a 32-bit floating point value to the stream in a binary format.
  6493. The binary 32-bit encoding of the float is written as a big-endian int.
  6494. @see InputStream::readFloatBigEndian
  6495. */
  6496. virtual void writeFloatBigEndian (float value);
  6497. /** Writes a 64-bit floating point value to the stream in a binary format.
  6498. The eight raw bytes of the double value are written out as a little-endian 64-bit int.
  6499. @see InputStream::readDouble
  6500. */
  6501. virtual void writeDouble (double value);
  6502. /** Writes a 64-bit floating point value to the stream in a binary format.
  6503. The eight raw bytes of the double value are written out as a big-endian 64-bit int.
  6504. @see InputStream::readDoubleBigEndian
  6505. */
  6506. virtual void writeDoubleBigEndian (double value);
  6507. /** Writes a byte to the output stream a given number of times. */
  6508. virtual void writeRepeatedByte (uint8 byte, int numTimesToRepeat);
  6509. /** Writes a condensed binary encoding of a 32-bit integer.
  6510. If you're storing a lot of integers which are unlikely to have very large values,
  6511. this can save a lot of space, because values under 0xff will only take up 2 bytes,
  6512. under 0xffff only 3 bytes, etc.
  6513. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6514. @see InputStream::readCompressedInt
  6515. */
  6516. virtual void writeCompressedInt (int value);
  6517. /** Stores a string in the stream in a binary format.
  6518. This isn't the method to use if you're trying to append text to the end of a
  6519. text-file! It's intended for storing a string so that it can be retrieved later
  6520. by InputStream::readString().
  6521. It writes the string to the stream as UTF8, including the null termination character.
  6522. For appending text to a file, instead use writeText, or operator<<
  6523. @see InputStream::readString, writeText, operator<<
  6524. */
  6525. virtual void writeString (const String& text);
  6526. /** Writes a string of text to the stream.
  6527. It can either write the text as UTF-8 or UTF-16, and can also add the UTF-16 byte-order-mark
  6528. bytes (0xff, 0xfe) to indicate the endianness (these should only be used at the start
  6529. of a file).
  6530. The method also replaces '\\n' characters in the text with '\\r\\n'.
  6531. */
  6532. virtual void writeText (const String& text,
  6533. bool asUTF16,
  6534. bool writeUTF16ByteOrderMark);
  6535. /** Reads data from an input stream and writes it to this stream.
  6536. @param source the stream to read from
  6537. @param maxNumBytesToWrite the number of bytes to read from the stream (if this is
  6538. less than zero, it will keep reading until the input
  6539. is exhausted)
  6540. */
  6541. virtual int writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite);
  6542. /** Sets the string that will be written to the stream when the writeNewLine()
  6543. method is called.
  6544. By default this will be set the the value of NewLine::getDefault().
  6545. */
  6546. void setNewLineString (const String& newLineString);
  6547. /** Returns the current new-line string that was set by setNewLineString(). */
  6548. const String& getNewLineString() const noexcept { return newLineString; }
  6549. private:
  6550. String newLineString;
  6551. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OutputStream);
  6552. };
  6553. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  6554. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, int number);
  6555. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  6556. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, double number);
  6557. /** Writes a character to a stream. */
  6558. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, char character);
  6559. /** Writes a null-terminated text string to a stream. */
  6560. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* text);
  6561. /** Writes a block of data from a MemoryBlock to a stream. */
  6562. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data);
  6563. /** Writes the contents of a file to a stream. */
  6564. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead);
  6565. /** Writes a new-line to a stream.
  6566. You can use the predefined symbol 'newLine' to invoke this, e.g.
  6567. @code
  6568. myOutputStream << "Hello World" << newLine << newLine;
  6569. @endcode
  6570. @see OutputStream::setNewLineString
  6571. */
  6572. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const NewLine&);
  6573. #endif // __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6574. /*** End of inlined file: juce_OutputStream.h ***/
  6575. /*** Start of inlined file: juce_InputStream.h ***/
  6576. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  6577. #define __JUCE_INPUTSTREAM_JUCEHEADER__
  6578. class MemoryBlock;
  6579. /** The base class for streams that read data.
  6580. Input and output streams are used throughout the library - subclasses can override
  6581. some or all of the virtual functions to implement their behaviour.
  6582. @see OutputStream, MemoryInputStream, BufferedInputStream, FileInputStream
  6583. */
  6584. class JUCE_API InputStream
  6585. {
  6586. public:
  6587. /** Destructor. */
  6588. virtual ~InputStream() {}
  6589. /** Returns the total number of bytes available for reading in this stream.
  6590. Note that this is the number of bytes available from the start of the
  6591. stream, not from the current position.
  6592. If the size of the stream isn't actually known, this may return -1.
  6593. */
  6594. virtual int64 getTotalLength() = 0;
  6595. /** Returns true if the stream has no more data to read. */
  6596. virtual bool isExhausted() = 0;
  6597. /** Reads a set of bytes from the stream into a memory buffer.
  6598. This is the only read method that subclasses actually need to implement, as the
  6599. InputStream base class implements the other read methods in terms of this one (although
  6600. it's often more efficient for subclasses to implement them directly).
  6601. @param destBuffer the destination buffer for the data
  6602. @param maxBytesToRead the maximum number of bytes to read - make sure the
  6603. memory block passed in is big enough to contain this
  6604. many bytes.
  6605. @returns the actual number of bytes that were read, which may be less than
  6606. maxBytesToRead if the stream is exhausted before it gets that far
  6607. */
  6608. virtual int read (void* destBuffer, int maxBytesToRead) = 0;
  6609. /** Reads a byte from the stream.
  6610. If the stream is exhausted, this will return zero.
  6611. @see OutputStream::writeByte
  6612. */
  6613. virtual char readByte();
  6614. /** Reads a boolean from the stream.
  6615. The bool is encoded as a single byte - 1 for true, 0 for false.
  6616. If the stream is exhausted, this will return false.
  6617. @see OutputStream::writeBool
  6618. */
  6619. virtual bool readBool();
  6620. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6621. If the next two bytes read are byte1 and byte2, this returns
  6622. (byte1 | (byte2 << 8)).
  6623. If the stream is exhausted partway through reading the bytes, this will return zero.
  6624. @see OutputStream::writeShort, readShortBigEndian
  6625. */
  6626. virtual short readShort();
  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. (byte2 | (byte1 << 8)).
  6630. If the stream is exhausted partway through reading the bytes, this will return zero.
  6631. @see OutputStream::writeShortBigEndian, readShort
  6632. */
  6633. virtual short readShortBigEndian();
  6634. /** Reads four bytes from the stream as a little-endian 32-bit value.
  6635. If the next four bytes are byte1 to byte4, this returns
  6636. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24)).
  6637. If the stream is exhausted partway through reading the bytes, this will return zero.
  6638. @see OutputStream::writeInt, readIntBigEndian
  6639. */
  6640. virtual int readInt();
  6641. /** Reads four bytes from the stream as a big-endian 32-bit value.
  6642. If the next four bytes are byte1 to byte4, this returns
  6643. (byte4 | (byte3 << 8) | (byte2 << 16) | (byte1 << 24)).
  6644. If the stream is exhausted partway through reading the bytes, this will return zero.
  6645. @see OutputStream::writeIntBigEndian, readInt
  6646. */
  6647. virtual int readIntBigEndian();
  6648. /** Reads eight bytes from the stream as a little-endian 64-bit value.
  6649. If the next eight bytes are byte1 to byte8, this returns
  6650. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24) | (byte5 << 32) | (byte6 << 40) | (byte7 << 48) | (byte8 << 56)).
  6651. If the stream is exhausted partway through reading the bytes, this will return zero.
  6652. @see OutputStream::writeInt64, readInt64BigEndian
  6653. */
  6654. virtual int64 readInt64();
  6655. /** Reads eight bytes from the stream as a big-endian 64-bit value.
  6656. If the next eight bytes are byte1 to byte8, this returns
  6657. (byte8 | (byte7 << 8) | (byte6 << 16) | (byte5 << 24) | (byte4 << 32) | (byte3 << 40) | (byte2 << 48) | (byte1 << 56)).
  6658. If the stream is exhausted partway through reading the bytes, this will return zero.
  6659. @see OutputStream::writeInt64BigEndian, readInt64
  6660. */
  6661. virtual int64 readInt64BigEndian();
  6662. /** Reads four bytes as a 32-bit floating point value.
  6663. The raw 32-bit encoding of the float is read from the stream as a little-endian int.
  6664. If the stream is exhausted partway through reading the bytes, this will return zero.
  6665. @see OutputStream::writeFloat, readDouble
  6666. */
  6667. virtual float readFloat();
  6668. /** Reads four bytes as a 32-bit floating point value.
  6669. The raw 32-bit encoding of the float is read from the stream as a big-endian int.
  6670. If the stream is exhausted partway through reading the bytes, this will return zero.
  6671. @see OutputStream::writeFloatBigEndian, readDoubleBigEndian
  6672. */
  6673. virtual float readFloatBigEndian();
  6674. /** Reads eight bytes as a 64-bit floating point value.
  6675. The raw 64-bit encoding of the double is read from the stream as a little-endian int64.
  6676. If the stream is exhausted partway through reading the bytes, this will return zero.
  6677. @see OutputStream::writeDouble, readFloat
  6678. */
  6679. virtual double readDouble();
  6680. /** Reads eight bytes as a 64-bit floating point value.
  6681. The raw 64-bit encoding of the double is read from the stream as a big-endian int64.
  6682. If the stream is exhausted partway through reading the bytes, this will return zero.
  6683. @see OutputStream::writeDoubleBigEndian, readFloatBigEndian
  6684. */
  6685. virtual double readDoubleBigEndian();
  6686. /** Reads an encoded 32-bit number from the stream using a space-saving compressed format.
  6687. For small values, this is more space-efficient than using readInt() and OutputStream::writeInt()
  6688. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6689. @see OutputStream::writeCompressedInt()
  6690. */
  6691. virtual int readCompressedInt();
  6692. /** Reads a UTF8 string from the stream, up to the next linefeed or carriage return.
  6693. This will read up to the next "\n" or "\r\n" or end-of-stream.
  6694. After this call, the stream's position will be left pointing to the next character
  6695. following the line-feed, but the linefeeds aren't included in the string that
  6696. is returned.
  6697. */
  6698. virtual String readNextLine();
  6699. /** Reads a zero-terminated UTF8 string from the stream.
  6700. This will read characters from the stream until it hits a zero character or
  6701. end-of-stream.
  6702. @see OutputStream::writeString, readEntireStreamAsString
  6703. */
  6704. virtual String readString();
  6705. /** Tries to read the whole stream and turn it into a string.
  6706. This will read from the stream's current position until the end-of-stream, and
  6707. will try to make an educated guess about whether it's unicode or an 8-bit encoding.
  6708. */
  6709. virtual String readEntireStreamAsString();
  6710. /** Reads from the stream and appends the data to a MemoryBlock.
  6711. @param destBlock the block to append the data onto
  6712. @param maxNumBytesToRead if this is a positive value, it sets a limit to the number
  6713. of bytes that will be read - if it's negative, data
  6714. will be read until the stream is exhausted.
  6715. @returns the number of bytes that were added to the memory block
  6716. */
  6717. virtual int readIntoMemoryBlock (MemoryBlock& destBlock,
  6718. int maxNumBytesToRead = -1);
  6719. /** Returns the offset of the next byte that will be read from the stream.
  6720. @see setPosition
  6721. */
  6722. virtual int64 getPosition() = 0;
  6723. /** Tries to move the current read position of the stream.
  6724. The position is an absolute number of bytes from the stream's start.
  6725. Some streams might not be able to do this, in which case they should do
  6726. nothing and return false. Others might be able to manage it by resetting
  6727. themselves and skipping to the correct position, although this is
  6728. obviously a bit slow.
  6729. @returns true if the stream manages to reposition itself correctly
  6730. @see getPosition
  6731. */
  6732. virtual bool setPosition (int64 newPosition) = 0;
  6733. /** Reads and discards a number of bytes from the stream.
  6734. Some input streams might implement this efficiently, but the base
  6735. class will just keep reading data until the requisite number of bytes
  6736. have been done.
  6737. */
  6738. virtual void skipNextBytes (int64 numBytesToSkip);
  6739. protected:
  6740. InputStream() noexcept {}
  6741. private:
  6742. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InputStream);
  6743. };
  6744. #endif // __JUCE_INPUTSTREAM_JUCEHEADER__
  6745. /*** End of inlined file: juce_InputStream.h ***/
  6746. #ifndef DOXYGEN
  6747. class ReferenceCountedObject;
  6748. class DynamicObject;
  6749. #endif
  6750. /**
  6751. A variant class, that can be used to hold a range of primitive values.
  6752. A var object can hold a range of simple primitive values, strings, or
  6753. any kind of ReferenceCountedObject. The var class is intended to act like
  6754. the kind of values used in dynamic scripting languages.
  6755. You can save/load var objects either in a small, proprietary binary format
  6756. using writeToStream()/readFromStream(), or as JSON by using the JSON class.
  6757. @see JSON, DynamicObject
  6758. */
  6759. class JUCE_API var
  6760. {
  6761. public:
  6762. typedef const var (DynamicObject::*MethodFunction) (const var* arguments, int numArguments);
  6763. typedef Identifier identifier;
  6764. /** Creates a void variant. */
  6765. var() noexcept;
  6766. /** Destructor. */
  6767. ~var() noexcept;
  6768. /** A static var object that can be used where you need an empty variant object. */
  6769. static const var null;
  6770. var (const var& valueToCopy);
  6771. var (int value) noexcept;
  6772. var (int64 value) noexcept;
  6773. var (bool value) noexcept;
  6774. var (double value) noexcept;
  6775. var (const char* value);
  6776. var (const wchar_t* value);
  6777. var (const String& value);
  6778. var (const Array<var>& value);
  6779. var (ReferenceCountedObject* object);
  6780. var (MethodFunction method) noexcept;
  6781. const var& operator= (const var& valueToCopy);
  6782. const var& operator= (int value);
  6783. const var& operator= (int64 value);
  6784. const var& operator= (bool value);
  6785. const var& operator= (double value);
  6786. const var& operator= (const char* value);
  6787. const var& operator= (const wchar_t* value);
  6788. const var& operator= (const String& value);
  6789. const var& operator= (const Array<var>& value);
  6790. const var& operator= (ReferenceCountedObject* object);
  6791. const var& operator= (MethodFunction method);
  6792. void swapWith (var& other) noexcept;
  6793. operator int() const noexcept;
  6794. operator int64() const noexcept;
  6795. operator bool() const noexcept;
  6796. operator float() const noexcept;
  6797. operator double() const noexcept;
  6798. operator String() const;
  6799. String toString() const;
  6800. Array<var>* getArray() const noexcept;
  6801. ReferenceCountedObject* getObject() const noexcept;
  6802. DynamicObject* getDynamicObject() const noexcept;
  6803. bool isVoid() const noexcept;
  6804. bool isInt() const noexcept;
  6805. bool isInt64() const noexcept;
  6806. bool isBool() const noexcept;
  6807. bool isDouble() const noexcept;
  6808. bool isString() const noexcept;
  6809. bool isObject() const noexcept;
  6810. bool isArray() const noexcept;
  6811. bool isMethod() const noexcept;
  6812. /** Returns true if this var has the same value as the one supplied.
  6813. Note that this ignores the type, so a string var "123" and an integer var with the
  6814. value 123 are considered to be equal.
  6815. @see equalsWithSameType
  6816. */
  6817. bool equals (const var& other) const noexcept;
  6818. /** Returns true if this var has the same value and type as the one supplied.
  6819. This differs from equals() because e.g. "123" and 123 will be considered different.
  6820. @see equals
  6821. */
  6822. bool equalsWithSameType (const var& other) const noexcept;
  6823. /** If the var is an array, this returns the number of elements.
  6824. If the var isn't actually an array, this will return 0.
  6825. */
  6826. int size() const;
  6827. /** If the var is an array, this can be used to return one of its elements.
  6828. To call this method, you must make sure that the var is actually an array, and
  6829. that the index is a valid number. If these conditions aren't met, behaviour is
  6830. undefined.
  6831. For more control over the array's contents, you can call getArray() and manipulate
  6832. it directly as an Array\<var\>.
  6833. */
  6834. const var& operator[] (int arrayIndex) const;
  6835. /** If the var is an array, this can be used to return one of its elements.
  6836. To call this method, you must make sure that the var is actually an array, and
  6837. that the index is a valid number. If these conditions aren't met, behaviour is
  6838. undefined.
  6839. For more control over the array's contents, you can call getArray() and manipulate
  6840. it directly as an Array\<var\>.
  6841. */
  6842. var& operator[] (int arrayIndex);
  6843. /** Appends an element to the var, converting it to an array if it isn't already one.
  6844. If the var isn't an array, it will be converted to one, and if its value was non-void,
  6845. this value will be kept as the first element of the new array. The parameter value
  6846. will then be appended to it.
  6847. For more control over the array's contents, you can call getArray() and manipulate
  6848. it directly as an Array\<var\>.
  6849. */
  6850. void append (const var& valueToAppend);
  6851. /** Inserts an element to the var, converting it to an array if it isn't already one.
  6852. If the var isn't an array, it will be converted to one, and if its value was non-void,
  6853. this value will be kept as the first element of the new array. The parameter value
  6854. will then be inserted into it.
  6855. For more control over the array's contents, you can call getArray() and manipulate
  6856. it directly as an Array\<var\>.
  6857. */
  6858. void insert (int index, const var& value);
  6859. /** If the var is an array, this removes one of its elements.
  6860. If the index is out-of-range or the var isn't an array, nothing will be done.
  6861. For more control over the array's contents, you can call getArray() and manipulate
  6862. it directly as an Array\<var\>.
  6863. */
  6864. void remove (int index);
  6865. /** Treating the var as an array, this resizes it to contain the specified number of elements.
  6866. If the var isn't an array, it will be converted to one, and if its value was non-void,
  6867. this value will be kept as the first element of the new array before resizing.
  6868. For more control over the array's contents, you can call getArray() and manipulate
  6869. it directly as an Array\<var\>.
  6870. */
  6871. void resize (int numArrayElementsWanted);
  6872. /** If the var is an array, this searches it for the first occurrence of the specified value,
  6873. and returns its index.
  6874. If the var isn't an array, or if the value isn't found, this returns -1.
  6875. */
  6876. int indexOf (const var& value) const;
  6877. /** If this variant is an object, this returns one of its properties. */
  6878. var operator[] (const Identifier& propertyName) const;
  6879. /** If this variant is an object, this returns one of its properties. */
  6880. var operator[] (const char* propertyName) const;
  6881. /** If this variant is an object, this returns one of its properties, or a default
  6882. fallback value if the property is not set. */
  6883. var getProperty (const Identifier& propertyName, const var& defaultReturnValue) const;
  6884. /** If this variant is an object, this invokes one of its methods with no arguments. */
  6885. var call (const Identifier& method) const;
  6886. /** If this variant is an object, this invokes one of its methods with one argument. */
  6887. var call (const Identifier& method, const var& arg1) const;
  6888. /** If this variant is an object, this invokes one of its methods with 2 arguments. */
  6889. var call (const Identifier& method, const var& arg1, const var& arg2) const;
  6890. /** If this variant is an object, this invokes one of its methods with 3 arguments. */
  6891. var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3);
  6892. /** If this variant is an object, this invokes one of its methods with 4 arguments. */
  6893. var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const;
  6894. /** If this variant is an object, this invokes one of its methods with 5 arguments. */
  6895. var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const;
  6896. /** If this variant is an object, this invokes one of its methods with a list of arguments. */
  6897. var invoke (const Identifier& method, const var* arguments, int numArguments) const;
  6898. /** Writes a binary representation of this value to a stream.
  6899. The data can be read back later using readFromStream().
  6900. @see JSON
  6901. */
  6902. void writeToStream (OutputStream& output) const;
  6903. /** Reads back a stored binary representation of a value.
  6904. The data in the stream must have been written using writeToStream(), or this
  6905. will have unpredictable results.
  6906. @see JSON
  6907. */
  6908. static var readFromStream (InputStream& input);
  6909. private:
  6910. class VariantType; friend class VariantType;
  6911. class VariantType_Void; friend class VariantType_Void;
  6912. class VariantType_Int; friend class VariantType_Int;
  6913. class VariantType_Int64; friend class VariantType_Int64;
  6914. class VariantType_Double; friend class VariantType_Double;
  6915. class VariantType_Bool; friend class VariantType_Bool;
  6916. class VariantType_String; friend class VariantType_String;
  6917. class VariantType_Object; friend class VariantType_Object;
  6918. class VariantType_Array; friend class VariantType_Array;
  6919. class VariantType_Method; friend class VariantType_Method;
  6920. union ValueUnion
  6921. {
  6922. int intValue;
  6923. int64 int64Value;
  6924. bool boolValue;
  6925. double doubleValue;
  6926. char stringValue [sizeof (String)];
  6927. ReferenceCountedObject* objectValue;
  6928. Array<var>* arrayValue;
  6929. MethodFunction methodValue;
  6930. };
  6931. const VariantType* type;
  6932. ValueUnion value;
  6933. Array<var>* convertToArray();
  6934. friend class DynamicObject;
  6935. var invokeMethod (DynamicObject*, const var*, int) const;
  6936. };
  6937. /** Compares the values of two var objects, using the var::equals() comparison. */
  6938. bool operator== (const var& v1, const var& v2) noexcept;
  6939. /** Compares the values of two var objects, using the var::equals() comparison. */
  6940. bool operator!= (const var& v1, const var& v2) noexcept;
  6941. bool operator== (const var& v1, const String& v2);
  6942. bool operator!= (const var& v1, const String& v2);
  6943. bool operator== (const var& v1, const char* v2);
  6944. bool operator!= (const var& v1, const char* v2);
  6945. #endif // __JUCE_VARIANT_JUCEHEADER__
  6946. /*** End of inlined file: juce_Variant.h ***/
  6947. /*** Start of inlined file: juce_LinkedListPointer.h ***/
  6948. #ifndef __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  6949. #define __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  6950. /**
  6951. Helps to manipulate singly-linked lists of objects.
  6952. For objects that are designed to contain a pointer to the subsequent item in the
  6953. list, this class contains methods to deal with the list. To use it, the ObjectType
  6954. class that it points to must contain a LinkedListPointer called nextListItem, e.g.
  6955. @code
  6956. struct MyObject
  6957. {
  6958. int x, y, z;
  6959. // A linkable object must contain a member with this name and type, which must be
  6960. // accessible by the LinkedListPointer class. (This doesn't mean it has to be public -
  6961. // you could make your class a friend of a LinkedListPointer<MyObject> instead).
  6962. LinkedListPointer<MyObject> nextListItem;
  6963. };
  6964. LinkedListPointer<MyObject> myList;
  6965. myList.append (new MyObject());
  6966. myList.append (new MyObject());
  6967. int numItems = myList.size(); // returns 2
  6968. MyObject* lastInList = myList.getLast();
  6969. @endcode
  6970. */
  6971. template <class ObjectType>
  6972. class LinkedListPointer
  6973. {
  6974. public:
  6975. /** Creates a null pointer to an empty list. */
  6976. LinkedListPointer() noexcept
  6977. : item (nullptr)
  6978. {
  6979. }
  6980. /** Creates a pointer to a list whose head is the item provided. */
  6981. explicit LinkedListPointer (ObjectType* const headItem) noexcept
  6982. : item (headItem)
  6983. {
  6984. }
  6985. /** Sets this pointer to point to a new list. */
  6986. LinkedListPointer& operator= (ObjectType* const newItem) noexcept
  6987. {
  6988. item = newItem;
  6989. return *this;
  6990. }
  6991. /** Returns the item which this pointer points to. */
  6992. inline operator ObjectType*() const noexcept
  6993. {
  6994. return item;
  6995. }
  6996. /** Returns the item which this pointer points to. */
  6997. inline ObjectType* get() const noexcept
  6998. {
  6999. return item;
  7000. }
  7001. /** Returns the last item in the list which this pointer points to.
  7002. This will iterate the list and return the last item found. Obviously the speed
  7003. of this operation will be proportional to the size of the list. If the list is
  7004. empty the return value will be this object.
  7005. If you're planning on appending a number of items to your list, it's much more
  7006. efficient to use the Appender class than to repeatedly call getLast() to find the end.
  7007. */
  7008. LinkedListPointer& getLast() noexcept
  7009. {
  7010. LinkedListPointer* l = this;
  7011. while (l->item != nullptr)
  7012. l = &(l->item->nextListItem);
  7013. return *l;
  7014. }
  7015. /** Returns the number of items in the list.
  7016. Obviously with a simple linked list, getting the size involves iterating the list, so
  7017. this can be a lengthy operation - be careful when using this method in your code.
  7018. */
  7019. int size() const noexcept
  7020. {
  7021. int total = 0;
  7022. for (ObjectType* i = item; i != nullptr; i = i->nextListItem)
  7023. ++total;
  7024. return total;
  7025. }
  7026. /** Returns the item at a given index in the list.
  7027. Since the only way to find an item is to iterate the list, this operation can obviously
  7028. be slow, depending on its size, so you should be careful when using this in algorithms.
  7029. */
  7030. LinkedListPointer& operator[] (int index) noexcept
  7031. {
  7032. LinkedListPointer* l = this;
  7033. while (--index >= 0 && l->item != nullptr)
  7034. l = &(l->item->nextListItem);
  7035. return *l;
  7036. }
  7037. /** Returns the item at a given index in the list.
  7038. Since the only way to find an item is to iterate the list, this operation can obviously
  7039. be slow, depending on its size, so you should be careful when using this in algorithms.
  7040. */
  7041. const LinkedListPointer& operator[] (int index) const noexcept
  7042. {
  7043. const LinkedListPointer* l = this;
  7044. while (--index >= 0 && l->item != nullptr)
  7045. l = &(l->item->nextListItem);
  7046. return *l;
  7047. }
  7048. /** Returns true if the list contains the given item. */
  7049. bool contains (const ObjectType* const itemToLookFor) const noexcept
  7050. {
  7051. for (ObjectType* i = item; i != nullptr; i = i->nextListItem)
  7052. if (itemToLookFor == i)
  7053. return true;
  7054. return false;
  7055. }
  7056. /** Inserts an item into the list, placing it before the item that this pointer
  7057. currently points to.
  7058. */
  7059. void insertNext (ObjectType* const newItem)
  7060. {
  7061. jassert (newItem != nullptr);
  7062. jassert (newItem->nextListItem == nullptr);
  7063. newItem->nextListItem = item;
  7064. item = newItem;
  7065. }
  7066. /** Inserts an item at a numeric index in the list.
  7067. Obviously this will involve iterating the list to find the item at the given index,
  7068. so be careful about the impact this may have on execution time.
  7069. */
  7070. void insertAtIndex (int index, ObjectType* newItem)
  7071. {
  7072. jassert (newItem != nullptr);
  7073. LinkedListPointer* l = this;
  7074. while (index != 0 && l->item != nullptr)
  7075. {
  7076. l = &(l->item->nextListItem);
  7077. --index;
  7078. }
  7079. l->insertNext (newItem);
  7080. }
  7081. /** Replaces the object that this pointer points to, appending the rest of the list to
  7082. the new object, and returning the old one.
  7083. */
  7084. ObjectType* replaceNext (ObjectType* const newItem) noexcept
  7085. {
  7086. jassert (newItem != nullptr);
  7087. jassert (newItem->nextListItem == nullptr);
  7088. ObjectType* const oldItem = item;
  7089. item = newItem;
  7090. item->nextListItem = oldItem->nextListItem.item;
  7091. oldItem->nextListItem = (ObjectType*) 0;
  7092. return oldItem;
  7093. }
  7094. /** Adds an item to the end of the list.
  7095. This operation involves iterating the whole list, so can be slow - if you need to
  7096. append a number of items to your list, it's much more efficient to use the Appender
  7097. class than to repeatedly call append().
  7098. */
  7099. void append (ObjectType* const newItem)
  7100. {
  7101. getLast().item = newItem;
  7102. }
  7103. /** Creates copies of all the items in another list and adds them to this one.
  7104. This will use the ObjectType's copy constructor to try to create copies of each
  7105. item in the other list, and appends them to this list.
  7106. */
  7107. void addCopyOfList (const LinkedListPointer& other)
  7108. {
  7109. LinkedListPointer* insertPoint = this;
  7110. for (ObjectType* i = other.item; i != nullptr; i = i->nextListItem)
  7111. {
  7112. insertPoint->insertNext (new ObjectType (*i));
  7113. insertPoint = &(insertPoint->item->nextListItem);
  7114. }
  7115. }
  7116. /** Removes the head item from the list.
  7117. This won't delete the object that is removed, but returns it, so the caller can
  7118. delete it if necessary.
  7119. */
  7120. ObjectType* removeNext() noexcept
  7121. {
  7122. ObjectType* const oldItem = item;
  7123. if (oldItem != nullptr)
  7124. {
  7125. item = oldItem->nextListItem;
  7126. oldItem->nextListItem = (ObjectType*) 0;
  7127. }
  7128. return oldItem;
  7129. }
  7130. /** Removes a specific item from the list.
  7131. Note that this will not delete the item, it simply unlinks it from the list.
  7132. */
  7133. void remove (ObjectType* const itemToRemove)
  7134. {
  7135. LinkedListPointer* const l = findPointerTo (itemToRemove);
  7136. if (l != nullptr)
  7137. l->removeNext();
  7138. }
  7139. /** Iterates the list, calling the delete operator on all of its elements and
  7140. leaving this pointer empty.
  7141. */
  7142. void deleteAll()
  7143. {
  7144. while (item != nullptr)
  7145. {
  7146. ObjectType* const oldItem = item;
  7147. item = oldItem->nextListItem;
  7148. delete oldItem;
  7149. }
  7150. }
  7151. /** Finds a pointer to a given item.
  7152. If the item is found in the list, this returns the pointer that points to it. If
  7153. the item isn't found, this returns null.
  7154. */
  7155. LinkedListPointer* findPointerTo (ObjectType* const itemToLookFor) noexcept
  7156. {
  7157. LinkedListPointer* l = this;
  7158. while (l->item != nullptr)
  7159. {
  7160. if (l->item == itemToLookFor)
  7161. return l;
  7162. l = &(l->item->nextListItem);
  7163. }
  7164. return nullptr;
  7165. }
  7166. /** Copies the items in the list to an array.
  7167. The destArray must contain enough elements to hold the entire list - no checks are
  7168. made for this!
  7169. */
  7170. void copyToArray (ObjectType** destArray) const noexcept
  7171. {
  7172. jassert (destArray != nullptr);
  7173. for (ObjectType* i = item; i != nullptr; i = i->nextListItem)
  7174. *destArray++ = i;
  7175. }
  7176. /**
  7177. Allows efficient repeated insertions into a list.
  7178. You can create an Appender object which points to the last element in your
  7179. list, and then repeatedly call Appender::append() to add items to the end
  7180. of the list in O(1) time.
  7181. */
  7182. class Appender
  7183. {
  7184. public:
  7185. /** Creates an appender which will add items to the given list.
  7186. */
  7187. Appender (LinkedListPointer& endOfListPointer) noexcept
  7188. : endOfList (&endOfListPointer)
  7189. {
  7190. // This can only be used to add to the end of a list.
  7191. jassert (endOfListPointer.item == nullptr);
  7192. }
  7193. /** Appends an item to the list. */
  7194. void append (ObjectType* const newItem) noexcept
  7195. {
  7196. *endOfList = newItem;
  7197. endOfList = &(newItem->nextListItem);
  7198. }
  7199. private:
  7200. LinkedListPointer* endOfList;
  7201. JUCE_DECLARE_NON_COPYABLE (Appender);
  7202. };
  7203. private:
  7204. ObjectType* item;
  7205. JUCE_DECLARE_NON_COPYABLE (LinkedListPointer);
  7206. };
  7207. #endif // __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  7208. /*** End of inlined file: juce_LinkedListPointer.h ***/
  7209. class XmlElement;
  7210. #ifndef DOXYGEN
  7211. class JSONFormatter;
  7212. #endif
  7213. /** Holds a set of named var objects.
  7214. This can be used as a basic structure to hold a set of var object, which can
  7215. be retrieved by using their identifier.
  7216. */
  7217. class JUCE_API NamedValueSet
  7218. {
  7219. public:
  7220. /** Creates an empty set. */
  7221. NamedValueSet() noexcept;
  7222. /** Creates a copy of another set. */
  7223. NamedValueSet (const NamedValueSet& other);
  7224. /** Replaces this set with a copy of another set. */
  7225. NamedValueSet& operator= (const NamedValueSet& other);
  7226. /** Destructor. */
  7227. ~NamedValueSet();
  7228. bool operator== (const NamedValueSet& other) const;
  7229. bool operator!= (const NamedValueSet& other) const;
  7230. /** Returns the total number of values that the set contains. */
  7231. int size() const noexcept;
  7232. /** Returns the value of a named item.
  7233. If the name isn't found, this will return a void variant.
  7234. @see getProperty
  7235. */
  7236. const var& operator[] (const Identifier& name) const;
  7237. /** Tries to return the named value, but if no such value is found, this will
  7238. instead return the supplied default value.
  7239. */
  7240. var getWithDefault (const Identifier& name, const var& defaultReturnValue) const;
  7241. /** Changes or adds a named value.
  7242. @returns true if a value was changed or added; false if the
  7243. value was already set the the value passed-in.
  7244. */
  7245. bool set (const Identifier& name, const var& newValue);
  7246. /** Returns true if the set contains an item with the specified name. */
  7247. bool contains (const Identifier& name) const;
  7248. /** Removes a value from the set.
  7249. @returns true if a value was removed; false if there was no value
  7250. with the name that was given.
  7251. */
  7252. bool remove (const Identifier& name);
  7253. /** Returns the name of the value at a given index.
  7254. The index must be between 0 and size() - 1.
  7255. */
  7256. const Identifier getName (int index) const;
  7257. /** Returns the value of the item at a given index.
  7258. The index must be between 0 and size() - 1.
  7259. */
  7260. const var& getValueAt (int index) const;
  7261. /** Removes all values. */
  7262. void clear();
  7263. /** Returns a pointer to the var that holds a named value, or null if there is
  7264. no value with this name.
  7265. Do not use this method unless you really need access to the internal var object
  7266. for some reason - for normal reading and writing always prefer operator[]() and set().
  7267. */
  7268. var* getVarPointer (const Identifier& name) const noexcept;
  7269. /** Sets properties to the values of all of an XML element's attributes. */
  7270. void setFromXmlAttributes (const XmlElement& xml);
  7271. /** Sets attributes in an XML element corresponding to each of this object's
  7272. properties.
  7273. */
  7274. void copyToXmlAttributes (XmlElement& xml) const;
  7275. private:
  7276. class NamedValue
  7277. {
  7278. public:
  7279. NamedValue() noexcept;
  7280. NamedValue (const NamedValue&);
  7281. NamedValue (const Identifier& name, const var& value);
  7282. NamedValue& operator= (const NamedValue&);
  7283. bool operator== (const NamedValue& other) const noexcept;
  7284. LinkedListPointer<NamedValue> nextListItem;
  7285. Identifier name;
  7286. var value;
  7287. private:
  7288. JUCE_LEAK_DETECTOR (NamedValue);
  7289. };
  7290. friend class LinkedListPointer<NamedValue>;
  7291. LinkedListPointer<NamedValue> values;
  7292. friend class JSONFormatter;
  7293. };
  7294. #endif // __JUCE_NAMEDVALUESET_JUCEHEADER__
  7295. /*** End of inlined file: juce_NamedValueSet.h ***/
  7296. /*** Start of inlined file: juce_ReferenceCountedObject.h ***/
  7297. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7298. #define __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7299. /**
  7300. Adds reference-counting to an object.
  7301. To add reference-counting to a class, derive it from this class, and
  7302. use the ReferenceCountedObjectPtr class to point to it.
  7303. e.g. @code
  7304. class MyClass : public ReferenceCountedObject
  7305. {
  7306. void foo();
  7307. // This is a neat way of declaring a typedef for a pointer class,
  7308. // rather than typing out the full templated name each time..
  7309. typedef ReferenceCountedObjectPtr<MyClass> Ptr;
  7310. };
  7311. MyClass::Ptr p = new MyClass();
  7312. MyClass::Ptr p2 = p;
  7313. p = nullptr;
  7314. p2->foo();
  7315. @endcode
  7316. Once a new ReferenceCountedObject has been assigned to a pointer, be
  7317. careful not to delete the object manually.
  7318. This class uses an Atomic<int> value to hold the reference count, so that it
  7319. the pointers can be passed between threads safely. For a faster but non-thread-safe
  7320. version, use SingleThreadedReferenceCountedObject instead.
  7321. @see ReferenceCountedObjectPtr, ReferenceCountedArray, SingleThreadedReferenceCountedObject
  7322. */
  7323. class JUCE_API ReferenceCountedObject
  7324. {
  7325. public:
  7326. /** Increments the object's reference count.
  7327. This is done automatically by the smart pointer, but is public just
  7328. in case it's needed for nefarious purposes.
  7329. */
  7330. inline void incReferenceCount() noexcept
  7331. {
  7332. ++refCount;
  7333. }
  7334. /** Decreases the object's reference count.
  7335. If the count gets to zero, the object will be deleted.
  7336. */
  7337. inline void decReferenceCount() noexcept
  7338. {
  7339. jassert (getReferenceCount() > 0);
  7340. if (--refCount == 0)
  7341. delete this;
  7342. }
  7343. /** Returns the object's current reference count. */
  7344. inline int getReferenceCount() const noexcept { return refCount.get(); }
  7345. protected:
  7346. /** Creates the reference-counted object (with an initial ref count of zero). */
  7347. ReferenceCountedObject()
  7348. {
  7349. }
  7350. /** Destructor. */
  7351. virtual ~ReferenceCountedObject()
  7352. {
  7353. // it's dangerous to delete an object that's still referenced by something else!
  7354. jassert (getReferenceCount() == 0);
  7355. }
  7356. private:
  7357. Atomic <int> refCount;
  7358. };
  7359. /**
  7360. Adds reference-counting to an object.
  7361. This is efectively a version of the ReferenceCountedObject class, but which
  7362. uses a non-atomic counter, and so is not thread-safe (but which will be more
  7363. efficient).
  7364. For more details on how to use it, see the ReferenceCountedObject class notes.
  7365. @see ReferenceCountedObject, ReferenceCountedObjectPtr, ReferenceCountedArray
  7366. */
  7367. class JUCE_API SingleThreadedReferenceCountedObject
  7368. {
  7369. public:
  7370. /** Increments the object's reference count.
  7371. This is done automatically by the smart pointer, but is public just
  7372. in case it's needed for nefarious purposes.
  7373. */
  7374. inline void incReferenceCount() noexcept
  7375. {
  7376. ++refCount;
  7377. }
  7378. /** Decreases the object's reference count.
  7379. If the count gets to zero, the object will be deleted.
  7380. */
  7381. inline void decReferenceCount() noexcept
  7382. {
  7383. jassert (getReferenceCount() > 0);
  7384. if (--refCount == 0)
  7385. delete this;
  7386. }
  7387. /** Returns the object's current reference count. */
  7388. inline int getReferenceCount() const noexcept { return refCount; }
  7389. protected:
  7390. /** Creates the reference-counted object (with an initial ref count of zero). */
  7391. SingleThreadedReferenceCountedObject() : refCount (0) {}
  7392. /** Destructor. */
  7393. virtual ~SingleThreadedReferenceCountedObject()
  7394. {
  7395. // it's dangerous to delete an object that's still referenced by something else!
  7396. jassert (getReferenceCount() == 0);
  7397. }
  7398. private:
  7399. int refCount;
  7400. };
  7401. /**
  7402. A smart-pointer class which points to a reference-counted object.
  7403. The template parameter specifies the class of the object you want to point to - the easiest
  7404. way to make a class reference-countable is to simply make it inherit from ReferenceCountedObject,
  7405. but if you need to, you could roll your own reference-countable class by implementing a pair of
  7406. mathods called incReferenceCount() and decReferenceCount().
  7407. When using this class, you'll probably want to create a typedef to abbreviate the full
  7408. templated name - e.g.
  7409. @code typedef ReferenceCountedObjectPtr<MyClass> MyClassPtr;@endcode
  7410. @see ReferenceCountedObject, ReferenceCountedObjectArray
  7411. */
  7412. template <class ReferenceCountedObjectClass>
  7413. class ReferenceCountedObjectPtr
  7414. {
  7415. public:
  7416. /** The class being referenced by this pointer. */
  7417. typedef ReferenceCountedObjectClass ReferencedType;
  7418. /** Creates a pointer to a null object. */
  7419. inline ReferenceCountedObjectPtr() noexcept
  7420. : referencedObject (nullptr)
  7421. {
  7422. }
  7423. /** Creates a pointer to an object.
  7424. This will increment the object's reference-count if it is non-null.
  7425. */
  7426. inline ReferenceCountedObjectPtr (ReferenceCountedObjectClass* const refCountedObject) noexcept
  7427. : referencedObject (refCountedObject)
  7428. {
  7429. if (refCountedObject != nullptr)
  7430. refCountedObject->incReferenceCount();
  7431. }
  7432. /** Copies another pointer.
  7433. This will increment the object's reference-count (if it is non-null).
  7434. */
  7435. inline ReferenceCountedObjectPtr (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other) noexcept
  7436. : referencedObject (other.referencedObject)
  7437. {
  7438. if (referencedObject != nullptr)
  7439. referencedObject->incReferenceCount();
  7440. }
  7441. /** Changes this pointer to point at a different object.
  7442. The reference count of the old object is decremented, and it might be
  7443. deleted if it hits zero. The new object's count is incremented.
  7444. */
  7445. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other)
  7446. {
  7447. ReferenceCountedObjectClass* const newObject = other.referencedObject;
  7448. if (newObject != referencedObject)
  7449. {
  7450. if (newObject != nullptr)
  7451. newObject->incReferenceCount();
  7452. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7453. referencedObject = newObject;
  7454. if (oldObject != nullptr)
  7455. oldObject->decReferenceCount();
  7456. }
  7457. return *this;
  7458. }
  7459. /** Changes this pointer to point at a different object.
  7460. The reference count of the old object is decremented, and it might be
  7461. deleted if it hits zero. The new object's count is incremented.
  7462. */
  7463. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (ReferenceCountedObjectClass* const newObject)
  7464. {
  7465. if (referencedObject != newObject)
  7466. {
  7467. if (newObject != nullptr)
  7468. newObject->incReferenceCount();
  7469. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7470. referencedObject = newObject;
  7471. if (oldObject != nullptr)
  7472. oldObject->decReferenceCount();
  7473. }
  7474. return *this;
  7475. }
  7476. /** Destructor.
  7477. This will decrement the object's reference-count, and may delete it if it
  7478. gets to zero.
  7479. */
  7480. inline ~ReferenceCountedObjectPtr()
  7481. {
  7482. if (referencedObject != nullptr)
  7483. referencedObject->decReferenceCount();
  7484. }
  7485. /** Returns the object that this pointer references.
  7486. The pointer returned may be zero, of course.
  7487. */
  7488. inline operator ReferenceCountedObjectClass*() const noexcept
  7489. {
  7490. return referencedObject;
  7491. }
  7492. // the -> operator is called on the referenced object
  7493. inline ReferenceCountedObjectClass* operator->() const noexcept
  7494. {
  7495. return referencedObject;
  7496. }
  7497. /** Returns the object that this pointer references.
  7498. The pointer returned may be zero, of course.
  7499. */
  7500. inline ReferenceCountedObjectClass* getObject() const noexcept
  7501. {
  7502. return referencedObject;
  7503. }
  7504. private:
  7505. ReferenceCountedObjectClass* referencedObject;
  7506. };
  7507. /** Compares two ReferenceCountedObjectPointers. */
  7508. template <class ReferenceCountedObjectClass>
  7509. bool operator== (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, ReferenceCountedObjectClass* const object2) noexcept
  7510. {
  7511. return object1.getObject() == object2;
  7512. }
  7513. /** Compares two ReferenceCountedObjectPointers. */
  7514. template <class ReferenceCountedObjectClass>
  7515. bool operator== (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) noexcept
  7516. {
  7517. return object1.getObject() == object2.getObject();
  7518. }
  7519. /** Compares two ReferenceCountedObjectPointers. */
  7520. template <class ReferenceCountedObjectClass>
  7521. bool operator== (ReferenceCountedObjectClass* object1, ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) noexcept
  7522. {
  7523. return object1 == object2.getObject();
  7524. }
  7525. /** Compares two ReferenceCountedObjectPointers. */
  7526. template <class ReferenceCountedObjectClass>
  7527. bool operator!= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, const ReferenceCountedObjectClass* object2) noexcept
  7528. {
  7529. return object1.getObject() != object2;
  7530. }
  7531. /** Compares two ReferenceCountedObjectPointers. */
  7532. template <class ReferenceCountedObjectClass>
  7533. bool operator!= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) noexcept
  7534. {
  7535. return object1.getObject() != object2.getObject();
  7536. }
  7537. /** Compares two ReferenceCountedObjectPointers. */
  7538. template <class ReferenceCountedObjectClass>
  7539. bool operator!= (ReferenceCountedObjectClass* object1, ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) noexcept
  7540. {
  7541. return object1 != object2.getObject();
  7542. }
  7543. #endif // __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7544. /*** End of inlined file: juce_ReferenceCountedObject.h ***/
  7545. /**
  7546. Represents a dynamically implemented object.
  7547. This class is primarily intended for wrapping scripting language objects,
  7548. but could be used for other purposes.
  7549. An instance of a DynamicObject can be used to store named properties, and
  7550. by subclassing hasMethod() and invokeMethod(), you can give your object
  7551. methods.
  7552. */
  7553. class JUCE_API DynamicObject : public ReferenceCountedObject
  7554. {
  7555. public:
  7556. DynamicObject();
  7557. /** Destructor. */
  7558. virtual ~DynamicObject();
  7559. /** Returns true if the object has a property with this name.
  7560. Note that if the property is actually a method, this will return false.
  7561. */
  7562. virtual bool hasProperty (const Identifier& propertyName) const;
  7563. /** Returns a named property.
  7564. This returns a void if no such property exists.
  7565. */
  7566. virtual var getProperty (const Identifier& propertyName) const;
  7567. /** Sets a named property. */
  7568. virtual void setProperty (const Identifier& propertyName, const var& newValue);
  7569. /** Removes a named property. */
  7570. virtual void removeProperty (const Identifier& propertyName);
  7571. /** Checks whether this object has the specified method.
  7572. The default implementation of this just checks whether there's a property
  7573. with this name that's actually a method, but this can be overridden for
  7574. building objects with dynamic invocation.
  7575. */
  7576. virtual bool hasMethod (const Identifier& methodName) const;
  7577. /** Invokes a named method on this object.
  7578. The default implementation looks up the named property, and if it's a method
  7579. call, then it invokes it.
  7580. This method is virtual to allow more dynamic invocation to used for objects
  7581. where the methods may not already be set as properies.
  7582. */
  7583. virtual var invokeMethod (const Identifier& methodName,
  7584. const var* parameters,
  7585. int numParameters);
  7586. /** Sets up a method.
  7587. This is basically the same as calling setProperty (methodName, (var::MethodFunction) myFunction), but
  7588. helps to avoid accidentally invoking the wrong type of var constructor. It also makes
  7589. the code easier to read,
  7590. The compiler will probably force you to use an explicit cast your method to a (var::MethodFunction), e.g.
  7591. @code
  7592. setMethod ("doSomething", (var::MethodFunction) &MyClass::doSomething);
  7593. @endcode
  7594. */
  7595. void setMethod (const Identifier& methodName,
  7596. var::MethodFunction methodFunction);
  7597. /** Removes all properties and methods from the object. */
  7598. void clear();
  7599. /** Returns the NamedValueSet that holds the object's properties. */
  7600. NamedValueSet& getProperties() noexcept { return properties; }
  7601. private:
  7602. NamedValueSet properties;
  7603. JUCE_LEAK_DETECTOR (DynamicObject);
  7604. };
  7605. #endif // __JUCE_DYNAMICOBJECT_JUCEHEADER__
  7606. /*** End of inlined file: juce_DynamicObject.h ***/
  7607. #endif
  7608. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  7609. #endif
  7610. #ifndef __JUCE_HASHMAP_JUCEHEADER__
  7611. /*** Start of inlined file: juce_HashMap.h ***/
  7612. #ifndef __JUCE_HASHMAP_JUCEHEADER__
  7613. #define __JUCE_HASHMAP_JUCEHEADER__
  7614. /*** Start of inlined file: juce_OwnedArray.h ***/
  7615. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  7616. #define __JUCE_OWNEDARRAY_JUCEHEADER__
  7617. /** An array designed for holding objects.
  7618. This holds a list of pointers to objects, and will automatically
  7619. delete the objects when they are removed from the array, or when the
  7620. array is itself deleted.
  7621. Declare it in the form: OwnedArray<MyObjectClass>
  7622. ..and then add new objects, e.g. myOwnedArray.add (new MyObjectClass());
  7623. After adding objects, they are 'owned' by the array and will be deleted when
  7624. removed or replaced.
  7625. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  7626. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7627. @see Array, ReferenceCountedArray, StringArray, CriticalSection
  7628. */
  7629. template <class ObjectClass,
  7630. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7631. class OwnedArray
  7632. {
  7633. public:
  7634. /** Creates an empty array. */
  7635. OwnedArray() noexcept
  7636. : numUsed (0)
  7637. {
  7638. }
  7639. /** Deletes the array and also deletes any objects inside it.
  7640. To get rid of the array without deleting its objects, use its
  7641. clear (false) method before deleting it.
  7642. */
  7643. ~OwnedArray()
  7644. {
  7645. clear (true);
  7646. }
  7647. /** Clears the array, optionally deleting the objects inside it first. */
  7648. void clear (const bool deleteObjects = true)
  7649. {
  7650. const ScopedLockType lock (getLock());
  7651. if (deleteObjects)
  7652. {
  7653. while (numUsed > 0)
  7654. delete data.elements [--numUsed];
  7655. }
  7656. data.setAllocatedSize (0);
  7657. numUsed = 0;
  7658. }
  7659. /** Returns the number of items currently in the array.
  7660. @see operator[]
  7661. */
  7662. inline int size() const noexcept
  7663. {
  7664. return numUsed;
  7665. }
  7666. /** Returns a pointer to the object at this index in the array.
  7667. If the index is out-of-range, this will return a null pointer, (and
  7668. it could be null anyway, because it's ok for the array to hold null
  7669. pointers as well as objects).
  7670. @see getUnchecked
  7671. */
  7672. inline ObjectClass* operator[] (const int index) const noexcept
  7673. {
  7674. const ScopedLockType lock (getLock());
  7675. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  7676. : static_cast <ObjectClass*> (nullptr);
  7677. }
  7678. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  7679. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  7680. it can be used when you're sure the index if always going to be legal.
  7681. */
  7682. inline ObjectClass* getUnchecked (const int index) const noexcept
  7683. {
  7684. const ScopedLockType lock (getLock());
  7685. jassert (isPositiveAndBelow (index, numUsed));
  7686. return data.elements [index];
  7687. }
  7688. /** Returns a pointer to the first object in the array.
  7689. This will return a null pointer if the array's empty.
  7690. @see getLast
  7691. */
  7692. inline ObjectClass* getFirst() const noexcept
  7693. {
  7694. const ScopedLockType lock (getLock());
  7695. return numUsed > 0 ? data.elements [0]
  7696. : static_cast <ObjectClass*> (nullptr);
  7697. }
  7698. /** Returns a pointer to the last object in the array.
  7699. This will return a null pointer if the array's empty.
  7700. @see getFirst
  7701. */
  7702. inline ObjectClass* getLast() const noexcept
  7703. {
  7704. const ScopedLockType lock (getLock());
  7705. return numUsed > 0 ? data.elements [numUsed - 1]
  7706. : static_cast <ObjectClass*> (nullptr);
  7707. }
  7708. /** Returns a pointer to the actual array data.
  7709. This pointer will only be valid until the next time a non-const method
  7710. is called on the array.
  7711. */
  7712. inline ObjectClass** getRawDataPointer() noexcept
  7713. {
  7714. return data.elements;
  7715. }
  7716. /** Returns a pointer to the first element in the array.
  7717. This method is provided for compatibility with standard C++ iteration mechanisms.
  7718. */
  7719. inline ObjectClass** begin() const noexcept
  7720. {
  7721. return data.elements;
  7722. }
  7723. /** Returns a pointer to the element which follows the last element in the array.
  7724. This method is provided for compatibility with standard C++ iteration mechanisms.
  7725. */
  7726. inline ObjectClass** end() const noexcept
  7727. {
  7728. return data.elements + numUsed;
  7729. }
  7730. /** Finds the index of an object which might be in the array.
  7731. @param objectToLookFor the object to look for
  7732. @returns the index at which the object was found, or -1 if it's not found
  7733. */
  7734. int indexOf (const ObjectClass* const objectToLookFor) const noexcept
  7735. {
  7736. const ScopedLockType lock (getLock());
  7737. ObjectClass* const* e = data.elements.getData();
  7738. ObjectClass* const* const end_ = e + numUsed;
  7739. for (; e != end_; ++e)
  7740. if (objectToLookFor == *e)
  7741. return static_cast <int> (e - data.elements.getData());
  7742. return -1;
  7743. }
  7744. /** Returns true if the array contains a specified object.
  7745. @param objectToLookFor the object to look for
  7746. @returns true if the object is in the array
  7747. */
  7748. bool contains (const ObjectClass* const objectToLookFor) const noexcept
  7749. {
  7750. const ScopedLockType lock (getLock());
  7751. ObjectClass* const* e = data.elements.getData();
  7752. ObjectClass* const* const end_ = e + numUsed;
  7753. for (; e != end_; ++e)
  7754. if (objectToLookFor == *e)
  7755. return true;
  7756. return false;
  7757. }
  7758. /** Appends a new object to the end of the array.
  7759. Note that the this object will be deleted by the OwnedArray when it
  7760. is removed, so be careful not to delete it somewhere else.
  7761. Also be careful not to add the same object to the array more than once,
  7762. as this will obviously cause deletion of dangling pointers.
  7763. @param newObject the new object to add to the array
  7764. @see set, insert, addIfNotAlreadyThere, addSorted
  7765. */
  7766. void add (const ObjectClass* const newObject) noexcept
  7767. {
  7768. const ScopedLockType lock (getLock());
  7769. data.ensureAllocatedSize (numUsed + 1);
  7770. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  7771. }
  7772. /** Inserts a new object into the array at the given index.
  7773. Note that the this object will be deleted by the OwnedArray when it
  7774. is removed, so be careful not to delete it somewhere else.
  7775. If the index is less than 0 or greater than the size of the array, the
  7776. element will be added to the end of the array.
  7777. Otherwise, it will be inserted into the array, moving all the later elements
  7778. along to make room.
  7779. Be careful not to add the same object to the array more than once,
  7780. as this will obviously cause deletion of dangling pointers.
  7781. @param indexToInsertAt the index at which the new element should be inserted
  7782. @param newObject the new object to add to the array
  7783. @see add, addSorted, addIfNotAlreadyThere, set
  7784. */
  7785. void insert (int indexToInsertAt,
  7786. const ObjectClass* const newObject) noexcept
  7787. {
  7788. if (indexToInsertAt >= 0)
  7789. {
  7790. const ScopedLockType lock (getLock());
  7791. if (indexToInsertAt > numUsed)
  7792. indexToInsertAt = numUsed;
  7793. data.ensureAllocatedSize (numUsed + 1);
  7794. ObjectClass** const e = data.elements + indexToInsertAt;
  7795. const int numToMove = numUsed - indexToInsertAt;
  7796. if (numToMove > 0)
  7797. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  7798. *e = const_cast <ObjectClass*> (newObject);
  7799. ++numUsed;
  7800. }
  7801. else
  7802. {
  7803. add (newObject);
  7804. }
  7805. }
  7806. /** Appends a new object at the end of the array as long as the array doesn't
  7807. already contain it.
  7808. If the array already contains a matching object, nothing will be done.
  7809. @param newObject the new object to add to the array
  7810. */
  7811. void addIfNotAlreadyThere (const ObjectClass* const newObject) noexcept
  7812. {
  7813. const ScopedLockType lock (getLock());
  7814. if (! contains (newObject))
  7815. add (newObject);
  7816. }
  7817. /** Replaces an object in the array with a different one.
  7818. If the index is less than zero, this method does nothing.
  7819. If the index is beyond the end of the array, the new object is added to the end of the array.
  7820. Be careful not to add the same object to the array more than once,
  7821. as this will obviously cause deletion of dangling pointers.
  7822. @param indexToChange the index whose value you want to change
  7823. @param newObject the new value to set for this index.
  7824. @param deleteOldElement whether to delete the object that's being replaced with the new one
  7825. @see add, insert, remove
  7826. */
  7827. void set (const int indexToChange,
  7828. const ObjectClass* const newObject,
  7829. const bool deleteOldElement = true)
  7830. {
  7831. if (indexToChange >= 0)
  7832. {
  7833. ObjectClass* toDelete = nullptr;
  7834. {
  7835. const ScopedLockType lock (getLock());
  7836. if (indexToChange < numUsed)
  7837. {
  7838. if (deleteOldElement)
  7839. {
  7840. toDelete = data.elements [indexToChange];
  7841. if (toDelete == newObject)
  7842. toDelete = nullptr;
  7843. }
  7844. data.elements [indexToChange] = const_cast <ObjectClass*> (newObject);
  7845. }
  7846. else
  7847. {
  7848. data.ensureAllocatedSize (numUsed + 1);
  7849. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  7850. }
  7851. }
  7852. delete toDelete; // don't want to use a ScopedPointer here because if the
  7853. // object has a private destructor, both OwnedArray and
  7854. // ScopedPointer would need to be friend classes..
  7855. }
  7856. else
  7857. {
  7858. jassertfalse; // you're trying to set an object at a negative index, which doesn't have
  7859. // any effect - but since the object is not being added, it may be leaking..
  7860. }
  7861. }
  7862. /** Adds elements from another array to the end of this array.
  7863. @param arrayToAddFrom the array from which to copy the elements
  7864. @param startIndex the first element of the other array to start copying from
  7865. @param numElementsToAdd how many elements to add from the other array. If this
  7866. value is negative or greater than the number of available elements,
  7867. all available elements will be copied.
  7868. @see add
  7869. */
  7870. template <class OtherArrayType>
  7871. void addArray (const OtherArrayType& arrayToAddFrom,
  7872. int startIndex = 0,
  7873. int numElementsToAdd = -1)
  7874. {
  7875. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  7876. const ScopedLockType lock2 (getLock());
  7877. if (startIndex < 0)
  7878. {
  7879. jassertfalse;
  7880. startIndex = 0;
  7881. }
  7882. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  7883. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  7884. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  7885. while (--numElementsToAdd >= 0)
  7886. {
  7887. data.elements [numUsed] = arrayToAddFrom.getUnchecked (startIndex++);
  7888. ++numUsed;
  7889. }
  7890. }
  7891. /** Adds copies of the elements in another array to the end of this array.
  7892. The other array must be either an OwnedArray of a compatible type of object, or an Array
  7893. containing pointers to the same kind of object. The objects involved must provide
  7894. a copy constructor, and this will be used to create new copies of each element, and
  7895. add them to this array.
  7896. @param arrayToAddFrom the array from which to copy the elements
  7897. @param startIndex the first element of the other array to start copying from
  7898. @param numElementsToAdd how many elements to add from the other array. If this
  7899. value is negative or greater than the number of available elements,
  7900. all available elements will be copied.
  7901. @see add
  7902. */
  7903. template <class OtherArrayType>
  7904. void addCopiesOf (const OtherArrayType& arrayToAddFrom,
  7905. int startIndex = 0,
  7906. int numElementsToAdd = -1)
  7907. {
  7908. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  7909. const ScopedLockType lock2 (getLock());
  7910. if (startIndex < 0)
  7911. {
  7912. jassertfalse;
  7913. startIndex = 0;
  7914. }
  7915. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  7916. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  7917. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  7918. while (--numElementsToAdd >= 0)
  7919. {
  7920. data.elements [numUsed] = new ObjectClass (*arrayToAddFrom.getUnchecked (startIndex++));
  7921. ++numUsed;
  7922. }
  7923. }
  7924. /** Inserts a new object into the array assuming that the array is sorted.
  7925. This will use a comparator to find the position at which the new object
  7926. should go. If the array isn't sorted, the behaviour of this
  7927. method will be unpredictable.
  7928. @param comparator the comparator to use to compare the elements - see the sort method
  7929. for details about this object's structure
  7930. @param newObject the new object to insert to the array
  7931. @returns the index at which the new object was added
  7932. @see add, sort, indexOfSorted
  7933. */
  7934. template <class ElementComparator>
  7935. int addSorted (ElementComparator& comparator, ObjectClass* const newObject) noexcept
  7936. {
  7937. (void) comparator; // if you pass in an object with a static compareElements() method, this
  7938. // avoids getting warning messages about the parameter being unused
  7939. const ScopedLockType lock (getLock());
  7940. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  7941. insert (index, newObject);
  7942. return index;
  7943. }
  7944. /** Finds the index of an object in the array, assuming that the array is sorted.
  7945. This will use a comparator to do a binary-chop to find the index of the given
  7946. element, if it exists. If the array isn't sorted, the behaviour of this
  7947. method will be unpredictable.
  7948. @param comparator the comparator to use to compare the elements - see the sort()
  7949. method for details about the form this object should take
  7950. @param objectToLookFor the object to search for
  7951. @returns the index of the element, or -1 if it's not found
  7952. @see addSorted, sort
  7953. */
  7954. template <class ElementComparator>
  7955. int indexOfSorted (ElementComparator& comparator,
  7956. const ObjectClass* const objectToLookFor) const noexcept
  7957. {
  7958. (void) comparator; // if you pass in an object with a static compareElements() method, this
  7959. // avoids getting warning messages about the parameter being unused
  7960. const ScopedLockType lock (getLock());
  7961. int start = 0;
  7962. int end_ = numUsed;
  7963. for (;;)
  7964. {
  7965. if (start >= end_)
  7966. {
  7967. return -1;
  7968. }
  7969. else if (comparator.compareElements (objectToLookFor, data.elements [start]) == 0)
  7970. {
  7971. return start;
  7972. }
  7973. else
  7974. {
  7975. const int halfway = (start + end_) >> 1;
  7976. if (halfway == start)
  7977. return -1;
  7978. else if (comparator.compareElements (objectToLookFor, data.elements [halfway]) >= 0)
  7979. start = halfway;
  7980. else
  7981. end_ = halfway;
  7982. }
  7983. }
  7984. }
  7985. /** Removes an object from the array.
  7986. This will remove the object at a given index (optionally also
  7987. deleting it) and move back all the subsequent objects to close the gap.
  7988. If the index passed in is out-of-range, nothing will happen.
  7989. @param indexToRemove the index of the element to remove
  7990. @param deleteObject whether to delete the object that is removed
  7991. @see removeObject, removeRange
  7992. */
  7993. void remove (const int indexToRemove,
  7994. const bool deleteObject = true)
  7995. {
  7996. ObjectClass* toDelete = nullptr;
  7997. {
  7998. const ScopedLockType lock (getLock());
  7999. if (isPositiveAndBelow (indexToRemove, numUsed))
  8000. {
  8001. ObjectClass** const e = data.elements + indexToRemove;
  8002. if (deleteObject)
  8003. toDelete = *e;
  8004. --numUsed;
  8005. const int numToShift = numUsed - indexToRemove;
  8006. if (numToShift > 0)
  8007. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  8008. }
  8009. }
  8010. delete toDelete; // don't want to use a ScopedPointer here because if the
  8011. // object has a private destructor, both OwnedArray and
  8012. // ScopedPointer would need to be friend classes..
  8013. if ((numUsed << 1) < data.numAllocated)
  8014. minimiseStorageOverheads();
  8015. }
  8016. /** Removes and returns an object from the array without deleting it.
  8017. This will remove the object at a given index and return it, moving back all
  8018. the subsequent objects to close the gap. If the index passed in is out-of-range,
  8019. nothing will happen.
  8020. @param indexToRemove the index of the element to remove
  8021. @see remove, removeObject, removeRange
  8022. */
  8023. ObjectClass* removeAndReturn (const int indexToRemove)
  8024. {
  8025. ObjectClass* removedItem = nullptr;
  8026. const ScopedLockType lock (getLock());
  8027. if (isPositiveAndBelow (indexToRemove, numUsed))
  8028. {
  8029. ObjectClass** const e = data.elements + indexToRemove;
  8030. removedItem = *e;
  8031. --numUsed;
  8032. const int numToShift = numUsed - indexToRemove;
  8033. if (numToShift > 0)
  8034. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  8035. if ((numUsed << 1) < data.numAllocated)
  8036. minimiseStorageOverheads();
  8037. }
  8038. return removedItem;
  8039. }
  8040. /** Removes a specified object from the array.
  8041. If the item isn't found, no action is taken.
  8042. @param objectToRemove the object to try to remove
  8043. @param deleteObject whether to delete the object (if it's found)
  8044. @see remove, removeRange
  8045. */
  8046. void removeObject (const ObjectClass* const objectToRemove,
  8047. const bool deleteObject = true)
  8048. {
  8049. const ScopedLockType lock (getLock());
  8050. ObjectClass** const e = data.elements.getData();
  8051. for (int i = 0; i < numUsed; ++i)
  8052. {
  8053. if (objectToRemove == e[i])
  8054. {
  8055. remove (i, deleteObject);
  8056. break;
  8057. }
  8058. }
  8059. }
  8060. /** Removes a range of objects from the array.
  8061. This will remove a set of objects, starting from the given index,
  8062. and move any subsequent elements down to close the gap.
  8063. If the range extends beyond the bounds of the array, it will
  8064. be safely clipped to the size of the array.
  8065. @param startIndex the index of the first object to remove
  8066. @param numberToRemove how many objects should be removed
  8067. @param deleteObjects whether to delete the objects that get removed
  8068. @see remove, removeObject
  8069. */
  8070. void removeRange (int startIndex,
  8071. const int numberToRemove,
  8072. const bool deleteObjects = true)
  8073. {
  8074. const ScopedLockType lock (getLock());
  8075. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  8076. startIndex = jlimit (0, numUsed, startIndex);
  8077. if (endIndex > startIndex)
  8078. {
  8079. if (deleteObjects)
  8080. {
  8081. for (int i = startIndex; i < endIndex; ++i)
  8082. {
  8083. delete data.elements [i];
  8084. data.elements [i] = nullptr; // (in case one of the destructors accesses this array and hits a dangling pointer)
  8085. }
  8086. }
  8087. const int rangeSize = endIndex - startIndex;
  8088. ObjectClass** e = data.elements + startIndex;
  8089. int numToShift = numUsed - endIndex;
  8090. numUsed -= rangeSize;
  8091. while (--numToShift >= 0)
  8092. {
  8093. *e = e [rangeSize];
  8094. ++e;
  8095. }
  8096. if ((numUsed << 1) < data.numAllocated)
  8097. minimiseStorageOverheads();
  8098. }
  8099. }
  8100. /** Removes the last n objects from the array.
  8101. @param howManyToRemove how many objects to remove from the end of the array
  8102. @param deleteObjects whether to also delete the objects that are removed
  8103. @see remove, removeObject, removeRange
  8104. */
  8105. void removeLast (int howManyToRemove = 1,
  8106. const bool deleteObjects = true)
  8107. {
  8108. const ScopedLockType lock (getLock());
  8109. if (howManyToRemove >= numUsed)
  8110. clear (deleteObjects);
  8111. else
  8112. removeRange (numUsed - howManyToRemove, howManyToRemove, deleteObjects);
  8113. }
  8114. /** Swaps a pair of objects in the array.
  8115. If either of the indexes passed in is out-of-range, nothing will happen,
  8116. otherwise the two objects at these positions will be exchanged.
  8117. */
  8118. void swap (const int index1,
  8119. const int index2) noexcept
  8120. {
  8121. const ScopedLockType lock (getLock());
  8122. if (isPositiveAndBelow (index1, numUsed)
  8123. && isPositiveAndBelow (index2, numUsed))
  8124. {
  8125. swapVariables (data.elements [index1],
  8126. data.elements [index2]);
  8127. }
  8128. }
  8129. /** Moves one of the objects to a different position.
  8130. This will move the object to a specified index, shuffling along
  8131. any intervening elements as required.
  8132. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  8133. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  8134. @param currentIndex the index of the object to be moved. If this isn't a
  8135. valid index, then nothing will be done
  8136. @param newIndex the index at which you'd like this object to end up. If this
  8137. is less than zero, it will be moved to the end of the array
  8138. */
  8139. void move (const int currentIndex,
  8140. int newIndex) noexcept
  8141. {
  8142. if (currentIndex != newIndex)
  8143. {
  8144. const ScopedLockType lock (getLock());
  8145. if (isPositiveAndBelow (currentIndex, numUsed))
  8146. {
  8147. if (! isPositiveAndBelow (newIndex, numUsed))
  8148. newIndex = numUsed - 1;
  8149. ObjectClass* const value = data.elements [currentIndex];
  8150. if (newIndex > currentIndex)
  8151. {
  8152. memmove (data.elements + currentIndex,
  8153. data.elements + currentIndex + 1,
  8154. (newIndex - currentIndex) * sizeof (ObjectClass*));
  8155. }
  8156. else
  8157. {
  8158. memmove (data.elements + newIndex + 1,
  8159. data.elements + newIndex,
  8160. (currentIndex - newIndex) * sizeof (ObjectClass*));
  8161. }
  8162. data.elements [newIndex] = value;
  8163. }
  8164. }
  8165. }
  8166. /** This swaps the contents of this array with those of another array.
  8167. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  8168. because it just swaps their internal pointers.
  8169. */
  8170. void swapWithArray (OwnedArray& otherArray) noexcept
  8171. {
  8172. const ScopedLockType lock1 (getLock());
  8173. const ScopedLockType lock2 (otherArray.getLock());
  8174. data.swapWith (otherArray.data);
  8175. swapVariables (numUsed, otherArray.numUsed);
  8176. }
  8177. /** Reduces the amount of storage being used by the array.
  8178. Arrays typically allocate slightly more storage than they need, and after
  8179. removing elements, they may have quite a lot of unused space allocated.
  8180. This method will reduce the amount of allocated storage to a minimum.
  8181. */
  8182. void minimiseStorageOverheads() noexcept
  8183. {
  8184. const ScopedLockType lock (getLock());
  8185. data.shrinkToNoMoreThan (numUsed);
  8186. }
  8187. /** Increases the array's internal storage to hold a minimum number of elements.
  8188. Calling this before adding a large known number of elements means that
  8189. the array won't have to keep dynamically resizing itself as the elements
  8190. are added, and it'll therefore be more efficient.
  8191. */
  8192. void ensureStorageAllocated (const int minNumElements) noexcept
  8193. {
  8194. const ScopedLockType lock (getLock());
  8195. data.ensureAllocatedSize (minNumElements);
  8196. }
  8197. /** Sorts the elements in the array.
  8198. This will use a comparator object to sort the elements into order. The object
  8199. passed must have a method of the form:
  8200. @code
  8201. int compareElements (ElementType first, ElementType second);
  8202. @endcode
  8203. ..and this method must return:
  8204. - a value of < 0 if the first comes before the second
  8205. - a value of 0 if the two objects are equivalent
  8206. - a value of > 0 if the second comes before the first
  8207. To improve performance, the compareElements() method can be declared as static or const.
  8208. @param comparator the comparator to use for comparing elements.
  8209. @param retainOrderOfEquivalentItems if this is true, then items
  8210. which the comparator says are equivalent will be
  8211. kept in the order in which they currently appear
  8212. in the array. This is slower to perform, but may
  8213. be important in some cases. If it's false, a faster
  8214. algorithm is used, but equivalent elements may be
  8215. rearranged.
  8216. @see sortArray, indexOfSorted
  8217. */
  8218. template <class ElementComparator>
  8219. void sort (ElementComparator& comparator,
  8220. const bool retainOrderOfEquivalentItems = false) const noexcept
  8221. {
  8222. (void) comparator; // if you pass in an object with a static compareElements() method, this
  8223. // avoids getting warning messages about the parameter being unused
  8224. const ScopedLockType lock (getLock());
  8225. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  8226. }
  8227. /** Returns the CriticalSection that locks this array.
  8228. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  8229. an object of ScopedLockType as an RAII lock for it.
  8230. */
  8231. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return data; }
  8232. /** Returns the type of scoped lock to use for locking this array */
  8233. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  8234. private:
  8235. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  8236. int numUsed;
  8237. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OwnedArray);
  8238. };
  8239. #endif // __JUCE_OWNEDARRAY_JUCEHEADER__
  8240. /*** End of inlined file: juce_OwnedArray.h ***/
  8241. /*** Start of inlined file: juce_ScopedPointer.h ***/
  8242. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8243. #define __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8244. /**
  8245. This class holds a pointer which is automatically deleted when this object goes
  8246. out of scope.
  8247. Once a pointer has been passed to a ScopedPointer, it will make sure that the pointer
  8248. gets deleted when the ScopedPointer is deleted. Using the ScopedPointer on the stack or
  8249. as member variables is a good way to use RAII to avoid accidentally leaking dynamically
  8250. created objects.
  8251. A ScopedPointer can be used in pretty much the same way that you'd use a normal pointer
  8252. to an object. If you use the assignment operator to assign a different object to a
  8253. ScopedPointer, the old one will be automatically deleted.
  8254. A const ScopedPointer is guaranteed not to lose ownership of its object or change the
  8255. object to which it points during its lifetime. This means that making a copy of a const
  8256. ScopedPointer is impossible, as that would involve the new copy taking ownership from the
  8257. old one.
  8258. If you need to get a pointer out of a ScopedPointer without it being deleted, you
  8259. can use the release() method.
  8260. */
  8261. template <class ObjectType>
  8262. class ScopedPointer
  8263. {
  8264. public:
  8265. /** Creates a ScopedPointer containing a null pointer. */
  8266. inline ScopedPointer() noexcept : object (nullptr)
  8267. {
  8268. }
  8269. /** Creates a ScopedPointer that owns the specified object. */
  8270. inline ScopedPointer (ObjectType* const objectToTakePossessionOf) noexcept
  8271. : object (objectToTakePossessionOf)
  8272. {
  8273. }
  8274. /** Creates a ScopedPointer that takes its pointer from another ScopedPointer.
  8275. Because a pointer can only belong to one ScopedPointer, this transfers
  8276. the pointer from the other object to this one, and the other object is reset to
  8277. be a null pointer.
  8278. */
  8279. ScopedPointer (ScopedPointer& objectToTransferFrom) noexcept
  8280. : object (objectToTransferFrom.object)
  8281. {
  8282. objectToTransferFrom.object = nullptr;
  8283. }
  8284. /** Destructor.
  8285. This will delete the object that this ScopedPointer currently refers to.
  8286. */
  8287. inline ~ScopedPointer() { delete object; }
  8288. /** Changes this ScopedPointer to point to a new object.
  8289. Because a pointer can only belong to one ScopedPointer, this transfers
  8290. the pointer from the other object to this one, and the other object is reset to
  8291. be a null pointer.
  8292. If this ScopedPointer already points to an object, that object
  8293. will first be deleted.
  8294. */
  8295. ScopedPointer& operator= (ScopedPointer& objectToTransferFrom)
  8296. {
  8297. if (this != objectToTransferFrom.getAddress())
  8298. {
  8299. // Two ScopedPointers should never be able to refer to the same object - if
  8300. // this happens, you must have done something dodgy!
  8301. jassert (object == nullptr || object != objectToTransferFrom.object);
  8302. ObjectType* const oldObject = object;
  8303. object = objectToTransferFrom.object;
  8304. objectToTransferFrom.object = nullptr;
  8305. delete oldObject;
  8306. }
  8307. return *this;
  8308. }
  8309. /** Changes this ScopedPointer to point to a new object.
  8310. If this ScopedPointer already points to an object, that object
  8311. will first be deleted.
  8312. The pointer that you pass is may be null.
  8313. */
  8314. ScopedPointer& operator= (ObjectType* const newObjectToTakePossessionOf)
  8315. {
  8316. if (object != newObjectToTakePossessionOf)
  8317. {
  8318. ObjectType* const oldObject = object;
  8319. object = newObjectToTakePossessionOf;
  8320. delete oldObject;
  8321. }
  8322. return *this;
  8323. }
  8324. /** Returns the object that this ScopedPointer refers to. */
  8325. inline operator ObjectType*() const noexcept { return object; }
  8326. /** Returns the object that this ScopedPointer refers to. */
  8327. inline ObjectType& operator*() const noexcept { return *object; }
  8328. /** Lets you access methods and properties of the object that this ScopedPointer refers to. */
  8329. inline ObjectType* operator->() const noexcept { return object; }
  8330. /** Removes the current object from this ScopedPointer without deleting it.
  8331. This will return the current object, and set the ScopedPointer to a null pointer.
  8332. */
  8333. ObjectType* release() noexcept { ObjectType* const o = object; object = nullptr; return o; }
  8334. /** Swaps this object with that of another ScopedPointer.
  8335. The two objects simply exchange their pointers.
  8336. */
  8337. void swapWith (ScopedPointer <ObjectType>& other) noexcept
  8338. {
  8339. // Two ScopedPointers should never be able to refer to the same object - if
  8340. // this happens, you must have done something dodgy!
  8341. jassert (object != other.object);
  8342. std::swap (object, other.object);
  8343. }
  8344. private:
  8345. ObjectType* object;
  8346. // (Required as an alternative to the overloaded & operator).
  8347. const ScopedPointer* getAddress() const noexcept { return this; }
  8348. #if ! JUCE_MSVC // (MSVC can't deal with multiple copy constructors)
  8349. /* This is private to stop people accidentally copying a const ScopedPointer (the compiler
  8350. would let you do so by implicitly casting the source to its raw object pointer).
  8351. A side effect of this is that you may hit a puzzling compiler error when you write something
  8352. like this:
  8353. ScopedPointer<MyClass> m = new MyClass(); // Compile error: copy constructor is private.
  8354. Even though the compiler would normally ignore the assignment here, it can't do so when the
  8355. copy constructor is private. It's very easy to fis though - just write it like this:
  8356. ScopedPointer<MyClass> m (new MyClass()); // Compiles OK
  8357. It's good practice to always use the latter form when writing your object declarations anyway,
  8358. rather than writing them as assignments and assuming (or hoping) that the compiler will be
  8359. smart enough to replace your construction + assignment with a single constructor.
  8360. */
  8361. ScopedPointer (const ScopedPointer&);
  8362. #endif
  8363. };
  8364. /** Compares a ScopedPointer with another pointer.
  8365. This can be handy for checking whether this is a null pointer.
  8366. */
  8367. template <class ObjectType>
  8368. bool operator== (const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) noexcept
  8369. {
  8370. return static_cast <ObjectType*> (pointer1) == pointer2;
  8371. }
  8372. /** Compares a ScopedPointer with another pointer.
  8373. This can be handy for checking whether this is a null pointer.
  8374. */
  8375. template <class ObjectType>
  8376. bool operator!= (const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) noexcept
  8377. {
  8378. return static_cast <ObjectType*> (pointer1) != pointer2;
  8379. }
  8380. #endif // __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8381. /*** End of inlined file: juce_ScopedPointer.h ***/
  8382. /**
  8383. A simple class to generate hash functions for some primitive types, intended for
  8384. use with the HashMap class.
  8385. @see HashMap
  8386. */
  8387. class DefaultHashFunctions
  8388. {
  8389. public:
  8390. /** Generates a simple hash from an integer. */
  8391. static int generateHash (const int key, const int upperLimit) noexcept { return std::abs (key) % upperLimit; }
  8392. /** Generates a simple hash from a string. */
  8393. static int generateHash (const String& key, const int upperLimit) noexcept { return (int) (((uint32) key.hashCode()) % upperLimit); }
  8394. /** Generates a simple hash from a variant. */
  8395. static int generateHash (const var& key, const int upperLimit) noexcept { return generateHash (key.toString(), upperLimit); }
  8396. };
  8397. /**
  8398. Holds a set of mappings between some key/value pairs.
  8399. The types of the key and value objects are set as template parameters.
  8400. You can also specify a class to supply a hash function that converts a key value
  8401. into an hashed integer. This class must have the form:
  8402. @code
  8403. struct MyHashGenerator
  8404. {
  8405. static int generateHash (MyKeyType key, int upperLimit)
  8406. {
  8407. // The function must return a value 0 <= x < upperLimit
  8408. return someFunctionOfMyKeyType (key) % upperLimit;
  8409. }
  8410. };
  8411. @endcode
  8412. Like the Array class, the key and value types are expected to be copy-by-value types, so
  8413. if you define them to be pointer types, this class won't delete the objects that they
  8414. point to.
  8415. If you don't supply a class for the HashFunctionToUse template parameter, the
  8416. default one provides some simple mappings for strings and ints.
  8417. @code
  8418. HashMap<int, String> hash;
  8419. hash.set (1, "item1");
  8420. hash.set (2, "item2");
  8421. DBG (hash [1]); // prints "item1"
  8422. DBG (hash [2]); // prints "item2"
  8423. // This iterates the map, printing all of its key -> value pairs..
  8424. for (HashMap<int, String>::Iterator i (hash); i.next();)
  8425. DBG (i.getKey() << " -> " << i.getValue());
  8426. @endcode
  8427. @see CriticalSection, DefaultHashFunctions, NamedValueSet, SortedSet
  8428. */
  8429. template <typename KeyType,
  8430. typename ValueType,
  8431. class HashFunctionToUse = DefaultHashFunctions,
  8432. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  8433. class HashMap
  8434. {
  8435. private:
  8436. typedef PARAMETER_TYPE (KeyType) KeyTypeParameter;
  8437. typedef PARAMETER_TYPE (ValueType) ValueTypeParameter;
  8438. public:
  8439. /** Creates an empty hash-map.
  8440. The numberOfSlots parameter specifies the number of hash entries the map will use. This
  8441. will be the "upperLimit" parameter that is passed to your generateHash() function. The number
  8442. of hash slots will grow automatically if necessary, or it can be remapped manually using remapTable().
  8443. */
  8444. explicit HashMap (const int numberOfSlots = defaultHashTableSize)
  8445. : totalNumItems (0)
  8446. {
  8447. slots.insertMultiple (0, nullptr, numberOfSlots);
  8448. }
  8449. /** Destructor. */
  8450. ~HashMap()
  8451. {
  8452. clear();
  8453. }
  8454. /** Removes all values from the map.
  8455. Note that this will clear the content, but won't affect the number of slots (see
  8456. remapTable and getNumSlots).
  8457. */
  8458. void clear()
  8459. {
  8460. const ScopedLockType sl (getLock());
  8461. for (int i = slots.size(); --i >= 0;)
  8462. {
  8463. HashEntry* h = slots.getUnchecked(i);
  8464. while (h != nullptr)
  8465. {
  8466. const ScopedPointer<HashEntry> deleter (h);
  8467. h = h->nextEntry;
  8468. }
  8469. slots.set (i, nullptr);
  8470. }
  8471. totalNumItems = 0;
  8472. }
  8473. /** Returns the current number of items in the map. */
  8474. inline int size() const noexcept
  8475. {
  8476. return totalNumItems;
  8477. }
  8478. /** Returns the value corresponding to a given key.
  8479. If the map doesn't contain the key, a default instance of the value type is returned.
  8480. @param keyToLookFor the key of the item being requested
  8481. */
  8482. inline const ValueType operator[] (KeyTypeParameter keyToLookFor) const
  8483. {
  8484. const ScopedLockType sl (getLock());
  8485. for (const HashEntry* entry = slots.getUnchecked (generateHashFor (keyToLookFor)); entry != nullptr; entry = entry->nextEntry)
  8486. if (entry->key == keyToLookFor)
  8487. return entry->value;
  8488. return ValueType();
  8489. }
  8490. /** Returns true if the map contains an item with the specied key. */
  8491. bool contains (KeyTypeParameter keyToLookFor) const
  8492. {
  8493. const ScopedLockType sl (getLock());
  8494. for (const HashEntry* entry = slots.getUnchecked (generateHashFor (keyToLookFor)); entry != nullptr; entry = entry->nextEntry)
  8495. if (entry->key == keyToLookFor)
  8496. return true;
  8497. return false;
  8498. }
  8499. /** Returns true if the hash contains at least one occurrence of a given value. */
  8500. bool containsValue (ValueTypeParameter valueToLookFor) const
  8501. {
  8502. const ScopedLockType sl (getLock());
  8503. for (int i = getNumSlots(); --i >= 0;)
  8504. for (const HashEntry* entry = slots.getUnchecked(i); entry != nullptr; entry = entry->nextEntry)
  8505. if (entry->value == valueToLookFor)
  8506. return true;
  8507. return false;
  8508. }
  8509. /** Adds or replaces an element in the hash-map.
  8510. If there's already an item with the given key, this will replace its value. Otherwise, a new item
  8511. will be added to the map.
  8512. */
  8513. void set (KeyTypeParameter newKey, ValueTypeParameter newValue)
  8514. {
  8515. const ScopedLockType sl (getLock());
  8516. const int hashIndex = generateHashFor (newKey);
  8517. HashEntry* const firstEntry = slots.getUnchecked (hashIndex);
  8518. for (HashEntry* entry = firstEntry; entry != nullptr; entry = entry->nextEntry)
  8519. {
  8520. if (entry->key == newKey)
  8521. {
  8522. entry->value = newValue;
  8523. return;
  8524. }
  8525. }
  8526. slots.set (hashIndex, new HashEntry (newKey, newValue, firstEntry));
  8527. ++totalNumItems;
  8528. if (totalNumItems > (getNumSlots() * 3) / 2)
  8529. remapTable (getNumSlots() * 2);
  8530. }
  8531. /** Removes an item with the given key. */
  8532. void remove (KeyTypeParameter keyToRemove)
  8533. {
  8534. const ScopedLockType sl (getLock());
  8535. const int hashIndex = generateHashFor (keyToRemove);
  8536. HashEntry* entry = slots.getUnchecked (hashIndex);
  8537. HashEntry* previous = nullptr;
  8538. while (entry != nullptr)
  8539. {
  8540. if (entry->key == keyToRemove)
  8541. {
  8542. const ScopedPointer<HashEntry> deleter (entry);
  8543. entry = entry->nextEntry;
  8544. if (previous != nullptr)
  8545. previous->nextEntry = entry;
  8546. else
  8547. slots.set (hashIndex, entry);
  8548. --totalNumItems;
  8549. }
  8550. else
  8551. {
  8552. previous = entry;
  8553. entry = entry->nextEntry;
  8554. }
  8555. }
  8556. }
  8557. /** Removes all items with the given value. */
  8558. void removeValue (ValueTypeParameter valueToRemove)
  8559. {
  8560. const ScopedLockType sl (getLock());
  8561. for (int i = getNumSlots(); --i >= 0;)
  8562. {
  8563. HashEntry* entry = slots.getUnchecked(i);
  8564. HashEntry* previous = nullptr;
  8565. while (entry != nullptr)
  8566. {
  8567. if (entry->value == valueToRemove)
  8568. {
  8569. const ScopedPointer<HashEntry> deleter (entry);
  8570. entry = entry->nextEntry;
  8571. if (previous != nullptr)
  8572. previous->nextEntry = entry;
  8573. else
  8574. slots.set (i, entry);
  8575. --totalNumItems;
  8576. }
  8577. else
  8578. {
  8579. previous = entry;
  8580. entry = entry->nextEntry;
  8581. }
  8582. }
  8583. }
  8584. }
  8585. /** Remaps the hash-map to use a different number of slots for its hash function.
  8586. Each slot corresponds to a single hash-code, and each one can contain multiple items.
  8587. @see getNumSlots()
  8588. */
  8589. void remapTable (int newNumberOfSlots)
  8590. {
  8591. HashMap newTable (newNumberOfSlots);
  8592. for (int i = getNumSlots(); --i >= 0;)
  8593. for (const HashEntry* entry = slots.getUnchecked(i); entry != nullptr; entry = entry->nextEntry)
  8594. newTable.set (entry->key, entry->value);
  8595. swapWith (newTable);
  8596. }
  8597. /** Returns the number of slots which are available for hashing.
  8598. Each slot corresponds to a single hash-code, and each one can contain multiple items.
  8599. @see getNumSlots()
  8600. */
  8601. inline int getNumSlots() const noexcept
  8602. {
  8603. return slots.size();
  8604. }
  8605. /** Efficiently swaps the contents of two hash-maps. */
  8606. void swapWith (HashMap& otherHashMap) noexcept
  8607. {
  8608. const ScopedLockType lock1 (getLock());
  8609. const ScopedLockType lock2 (otherHashMap.getLock());
  8610. slots.swapWithArray (otherHashMap.slots);
  8611. std::swap (totalNumItems, otherHashMap.totalNumItems);
  8612. }
  8613. /** Returns the CriticalSection that locks this structure.
  8614. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  8615. an object of ScopedLockType as an RAII lock for it.
  8616. */
  8617. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return lock; }
  8618. /** Returns the type of scoped lock to use for locking this array */
  8619. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  8620. private:
  8621. class HashEntry
  8622. {
  8623. public:
  8624. HashEntry (KeyTypeParameter key_, ValueTypeParameter value_, HashEntry* const nextEntry_)
  8625. : key (key_), value (value_), nextEntry (nextEntry_)
  8626. {}
  8627. const KeyType key;
  8628. ValueType value;
  8629. HashEntry* nextEntry;
  8630. JUCE_DECLARE_NON_COPYABLE (HashEntry);
  8631. };
  8632. public:
  8633. /** Iterates over the items in a HashMap.
  8634. To use it, repeatedly call next() until it returns false, e.g.
  8635. @code
  8636. HashMap <String, String> myMap;
  8637. HashMap<String, String>::Iterator i (myMap);
  8638. while (i.next())
  8639. {
  8640. DBG (i.getKey() << " -> " << i.getValue());
  8641. }
  8642. @endcode
  8643. The order in which items are iterated bears no resemblence to the order in which
  8644. they were originally added!
  8645. Obviously as soon as you call any non-const methods on the original hash-map, any
  8646. iterators that were created beforehand will cease to be valid, and should not be used.
  8647. @see HashMap
  8648. */
  8649. class Iterator
  8650. {
  8651. public:
  8652. Iterator (const HashMap& hashMapToIterate)
  8653. : hashMap (hashMapToIterate), entry (0), index (0)
  8654. {}
  8655. /** Moves to the next item, if one is available.
  8656. When this returns true, you can get the item's key and value using getKey() and
  8657. getValue(). If it returns false, the iteration has finished and you should stop.
  8658. */
  8659. bool next()
  8660. {
  8661. if (entry != nullptr)
  8662. entry = entry->nextEntry;
  8663. while (entry == nullptr)
  8664. {
  8665. if (index >= hashMap.getNumSlots())
  8666. return false;
  8667. entry = hashMap.slots.getUnchecked (index++);
  8668. }
  8669. return true;
  8670. }
  8671. /** Returns the current item's key.
  8672. This should only be called when a call to next() has just returned true.
  8673. */
  8674. const KeyType getKey() const
  8675. {
  8676. return entry != nullptr ? entry->key : KeyType();
  8677. }
  8678. /** Returns the current item's value.
  8679. This should only be called when a call to next() has just returned true.
  8680. */
  8681. const ValueType getValue() const
  8682. {
  8683. return entry != nullptr ? entry->value : ValueType();
  8684. }
  8685. private:
  8686. const HashMap& hashMap;
  8687. HashEntry* entry;
  8688. int index;
  8689. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Iterator);
  8690. };
  8691. private:
  8692. enum { defaultHashTableSize = 101 };
  8693. friend class Iterator;
  8694. Array <HashEntry*> slots;
  8695. int totalNumItems;
  8696. TypeOfCriticalSectionToUse lock;
  8697. int generateHashFor (KeyTypeParameter key) const
  8698. {
  8699. const int hash = HashFunctionToUse::generateHash (key, getNumSlots());
  8700. jassert (isPositiveAndBelow (hash, getNumSlots())); // your hash function is generating out-of-range numbers!
  8701. return hash;
  8702. }
  8703. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HashMap);
  8704. };
  8705. #endif // __JUCE_HASHMAP_JUCEHEADER__
  8706. /*** End of inlined file: juce_HashMap.h ***/
  8707. #endif
  8708. #ifndef __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  8709. #endif
  8710. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  8711. #endif
  8712. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  8713. #endif
  8714. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  8715. /*** Start of inlined file: juce_PropertySet.h ***/
  8716. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  8717. #define __JUCE_PROPERTYSET_JUCEHEADER__
  8718. /*** Start of inlined file: juce_StringPairArray.h ***/
  8719. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  8720. #define __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  8721. /*** Start of inlined file: juce_StringArray.h ***/
  8722. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  8723. #define __JUCE_STRINGARRAY_JUCEHEADER__
  8724. /**
  8725. A special array for holding a list of strings.
  8726. @see String, StringPairArray
  8727. */
  8728. class JUCE_API StringArray
  8729. {
  8730. public:
  8731. /** Creates an empty string array */
  8732. StringArray() noexcept;
  8733. /** Creates a copy of another string array */
  8734. StringArray (const StringArray& other);
  8735. /** Creates an array containing a single string. */
  8736. explicit StringArray (const String& firstValue);
  8737. /** Creates a copy of an array of string literals.
  8738. @param strings an array of strings to add. Null pointers in the array will be
  8739. treated as empty strings
  8740. @param numberOfStrings how many items there are in the array
  8741. */
  8742. StringArray (const char* const* strings, int numberOfStrings);
  8743. /** Creates a copy of a null-terminated array of string literals.
  8744. Each item from the array passed-in is added, until it encounters a null pointer,
  8745. at which point it stops.
  8746. */
  8747. explicit StringArray (const char* const* strings);
  8748. /** Creates a copy of a null-terminated array of string literals.
  8749. Each item from the array passed-in is added, until it encounters a null pointer,
  8750. at which point it stops.
  8751. */
  8752. explicit StringArray (const wchar_t* const* strings);
  8753. /** Creates a copy of an array of string literals.
  8754. @param strings an array of strings to add. Null pointers in the array will be
  8755. treated as empty strings
  8756. @param numberOfStrings how many items there are in the array
  8757. */
  8758. StringArray (const wchar_t* const* strings, int numberOfStrings);
  8759. /** Destructor. */
  8760. ~StringArray();
  8761. /** Copies the contents of another string array into this one */
  8762. StringArray& operator= (const StringArray& other);
  8763. /** Compares two arrays.
  8764. Comparisons are case-sensitive.
  8765. @returns true only if the other array contains exactly the same strings in the same order
  8766. */
  8767. bool operator== (const StringArray& other) const noexcept;
  8768. /** Compares two arrays.
  8769. Comparisons are case-sensitive.
  8770. @returns false if the other array contains exactly the same strings in the same order
  8771. */
  8772. bool operator!= (const StringArray& other) const noexcept;
  8773. /** Returns the number of strings in the array */
  8774. inline int size() const noexcept { return strings.size(); };
  8775. /** Returns one of the strings from the array.
  8776. If the index is out-of-range, an empty string is returned.
  8777. Obviously the reference returned shouldn't be stored for later use, as the
  8778. string it refers to may disappear when the array changes.
  8779. */
  8780. const String& operator[] (int index) const noexcept;
  8781. /** Returns a reference to one of the strings in the array.
  8782. This lets you modify a string in-place in the array, but you must be sure that
  8783. the index is in-range.
  8784. */
  8785. String& getReference (int index) noexcept;
  8786. /** Searches for a string in the array.
  8787. The comparison will be case-insensitive if the ignoreCase parameter is true.
  8788. @returns true if the string is found inside the array
  8789. */
  8790. bool contains (const String& stringToLookFor,
  8791. bool ignoreCase = false) const;
  8792. /** Searches for a string in the array.
  8793. The comparison will be case-insensitive if the ignoreCase parameter is true.
  8794. @param stringToLookFor the string to try to find
  8795. @param ignoreCase whether the comparison should be case-insensitive
  8796. @param startIndex the first index to start searching from
  8797. @returns the index of the first occurrence of the string in this array,
  8798. or -1 if it isn't found.
  8799. */
  8800. int indexOf (const String& stringToLookFor,
  8801. bool ignoreCase = false,
  8802. int startIndex = 0) const;
  8803. /** Appends a string at the end of the array. */
  8804. void add (const String& stringToAdd);
  8805. /** Inserts a string into the array.
  8806. This will insert a string into the array at the given index, moving
  8807. up the other elements to make room for it.
  8808. If the index is less than zero or greater than the size of the array,
  8809. the new string will be added to the end of the array.
  8810. */
  8811. void insert (int index, const String& stringToAdd);
  8812. /** Adds a string to the array as long as it's not already in there.
  8813. The search can optionally be case-insensitive.
  8814. */
  8815. void addIfNotAlreadyThere (const String& stringToAdd, bool ignoreCase = false);
  8816. /** Replaces one of the strings in the array with another one.
  8817. If the index is higher than the array's size, the new string will be
  8818. added to the end of the array; if it's less than zero nothing happens.
  8819. */
  8820. void set (int index, const String& newString);
  8821. /** Appends some strings from another array to the end of this one.
  8822. @param other the array to add
  8823. @param startIndex the first element of the other array to add
  8824. @param numElementsToAdd the maximum number of elements to add (if this is
  8825. less than zero, they are all added)
  8826. */
  8827. void addArray (const StringArray& other,
  8828. int startIndex = 0,
  8829. int numElementsToAdd = -1);
  8830. /** Breaks up a string into tokens and adds them to this array.
  8831. This will tokenise the given string using whitespace characters as the
  8832. token delimiters, and will add these tokens to the end of the array.
  8833. @returns the number of tokens added
  8834. */
  8835. int addTokens (const String& stringToTokenise,
  8836. bool preserveQuotedStrings);
  8837. /** Breaks up a string into tokens and adds them to this array.
  8838. This will tokenise the given string (using the string passed in to define the
  8839. token delimiters), and will add these tokens to the end of the array.
  8840. @param stringToTokenise the string to tokenise
  8841. @param breakCharacters a string of characters, any of which will be considered
  8842. to be a token delimiter.
  8843. @param quoteCharacters if this string isn't empty, it defines a set of characters
  8844. which are treated as quotes. Any text occurring
  8845. between quotes is not broken up into tokens.
  8846. @returns the number of tokens added
  8847. */
  8848. int addTokens (const String& stringToTokenise,
  8849. const String& breakCharacters,
  8850. const String& quoteCharacters);
  8851. /** Breaks up a string into lines and adds them to this array.
  8852. This breaks a string down into lines separated by \\n or \\r\\n, and adds each line
  8853. to the array. Line-break characters are omitted from the strings that are added to
  8854. the array.
  8855. */
  8856. int addLines (const String& stringToBreakUp);
  8857. /** Removes all elements from the array. */
  8858. void clear();
  8859. /** Removes a string from the array.
  8860. If the index is out-of-range, no action will be taken.
  8861. */
  8862. void remove (int index);
  8863. /** Finds a string in the array and removes it.
  8864. This will remove the first occurrence of the given string from the array. The
  8865. comparison may be case-insensitive depending on the ignoreCase parameter.
  8866. */
  8867. void removeString (const String& stringToRemove,
  8868. bool ignoreCase = false);
  8869. /** Removes a range of elements from the array.
  8870. This will remove a set of elements, starting from the given index,
  8871. and move subsequent elements down to close the gap.
  8872. If the range extends beyond the bounds of the array, it will
  8873. be safely clipped to the size of the array.
  8874. @param startIndex the index of the first element to remove
  8875. @param numberToRemove how many elements should be removed
  8876. */
  8877. void removeRange (int startIndex, int numberToRemove);
  8878. /** Removes any duplicated elements from the array.
  8879. If any string appears in the array more than once, only the first occurrence of
  8880. it will be retained.
  8881. @param ignoreCase whether to use a case-insensitive comparison
  8882. */
  8883. void removeDuplicates (bool ignoreCase);
  8884. /** Removes empty strings from the array.
  8885. @param removeWhitespaceStrings if true, strings that only contain whitespace
  8886. characters will also be removed
  8887. */
  8888. void removeEmptyStrings (bool removeWhitespaceStrings = true);
  8889. /** Moves one of the strings to a different position.
  8890. This will move the string to a specified index, shuffling along
  8891. any intervening elements as required.
  8892. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  8893. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  8894. @param currentIndex the index of the value to be moved. If this isn't a
  8895. valid index, then nothing will be done
  8896. @param newIndex the index at which you'd like this value to end up. If this
  8897. is less than zero, the value will be moved to the end
  8898. of the array
  8899. */
  8900. void move (int currentIndex, int newIndex) noexcept;
  8901. /** Deletes any whitespace characters from the starts and ends of all the strings. */
  8902. void trim();
  8903. /** Adds numbers to the strings in the array, to make each string unique.
  8904. This will add numbers to the ends of groups of similar strings.
  8905. e.g. if there are two "moose" strings, they will become "moose (1)" and "moose (2)"
  8906. @param ignoreCaseWhenComparing whether the comparison used is case-insensitive
  8907. @param appendNumberToFirstInstance whether the first of a group of similar strings
  8908. also has a number appended to it.
  8909. @param preNumberString when adding a number, this string is added before the number.
  8910. If you pass 0, a default string will be used, which adds
  8911. brackets around the number.
  8912. @param postNumberString this string is appended after any numbers that are added.
  8913. If you pass 0, a default string will be used, which adds
  8914. brackets around the number.
  8915. */
  8916. void appendNumbersToDuplicates (bool ignoreCaseWhenComparing,
  8917. bool appendNumberToFirstInstance,
  8918. CharPointer_UTF8 preNumberString = CharPointer_UTF8 (nullptr),
  8919. CharPointer_UTF8 postNumberString = CharPointer_UTF8 (nullptr));
  8920. /** Joins the strings in the array together into one string.
  8921. This will join a range of elements from the array into a string, separating
  8922. them with a given string.
  8923. e.g. joinIntoString (",") will turn an array of "a" "b" and "c" into "a,b,c".
  8924. @param separatorString the string to insert between all the strings
  8925. @param startIndex the first element to join
  8926. @param numberOfElements how many elements to join together. If this is less
  8927. than zero, all available elements will be used.
  8928. */
  8929. String joinIntoString (const String& separatorString,
  8930. int startIndex = 0,
  8931. int numberOfElements = -1) const;
  8932. /** Sorts the array into alphabetical order.
  8933. @param ignoreCase if true, the comparisons used will be case-sensitive.
  8934. */
  8935. void sort (bool ignoreCase);
  8936. /** Reduces the amount of storage being used by the array.
  8937. Arrays typically allocate slightly more storage than they need, and after
  8938. removing elements, they may have quite a lot of unused space allocated.
  8939. This method will reduce the amount of allocated storage to a minimum.
  8940. */
  8941. void minimiseStorageOverheads();
  8942. private:
  8943. Array <String> strings;
  8944. JUCE_LEAK_DETECTOR (StringArray);
  8945. };
  8946. #endif // __JUCE_STRINGARRAY_JUCEHEADER__
  8947. /*** End of inlined file: juce_StringArray.h ***/
  8948. /**
  8949. A container for holding a set of strings which are keyed by another string.
  8950. @see StringArray
  8951. */
  8952. class JUCE_API StringPairArray
  8953. {
  8954. public:
  8955. /** Creates an empty array */
  8956. StringPairArray (bool ignoreCaseWhenComparingKeys = true);
  8957. /** Creates a copy of another array */
  8958. StringPairArray (const StringPairArray& other);
  8959. /** Destructor. */
  8960. ~StringPairArray();
  8961. /** Copies the contents of another string array into this one */
  8962. StringPairArray& operator= (const StringPairArray& other);
  8963. /** Compares two arrays.
  8964. Comparisons are case-sensitive.
  8965. @returns true only if the other array contains exactly the same strings with the same keys
  8966. */
  8967. bool operator== (const StringPairArray& other) const;
  8968. /** Compares two arrays.
  8969. Comparisons are case-sensitive.
  8970. @returns false if the other array contains exactly the same strings with the same keys
  8971. */
  8972. bool operator!= (const StringPairArray& other) const;
  8973. /** Finds the value corresponding to a key string.
  8974. If no such key is found, this will just return an empty string. To check whether
  8975. a given key actually exists (because it might actually be paired with an empty string), use
  8976. the getAllKeys() method to obtain a list.
  8977. Obviously the reference returned shouldn't be stored for later use, as the
  8978. string it refers to may disappear when the array changes.
  8979. @see getValue
  8980. */
  8981. const String& operator[] (const String& key) const;
  8982. /** Finds the value corresponding to a key string.
  8983. If no such key is found, this will just return the value provided as a default.
  8984. @see operator[]
  8985. */
  8986. String getValue (const String& key, const String& defaultReturnValue) const;
  8987. /** Returns a list of all keys in the array. */
  8988. const StringArray& getAllKeys() const noexcept { return keys; }
  8989. /** Returns a list of all values in the array. */
  8990. const StringArray& getAllValues() const noexcept { return values; }
  8991. /** Returns the number of strings in the array */
  8992. inline int size() const noexcept { return keys.size(); };
  8993. /** Adds or amends a key/value pair.
  8994. If a value already exists with this key, its value will be overwritten,
  8995. otherwise the key/value pair will be added to the array.
  8996. */
  8997. void set (const String& key, const String& value);
  8998. /** Adds the items from another array to this one.
  8999. This is equivalent to using set() to add each of the pairs from the other array.
  9000. */
  9001. void addArray (const StringPairArray& other);
  9002. /** Removes all elements from the array. */
  9003. void clear();
  9004. /** Removes a string from the array based on its key.
  9005. If the key isn't found, nothing will happen.
  9006. */
  9007. void remove (const String& key);
  9008. /** Removes a string from the array based on its index.
  9009. If the index is out-of-range, no action will be taken.
  9010. */
  9011. void remove (int index);
  9012. /** Indicates whether to use a case-insensitive search when looking up a key string.
  9013. */
  9014. void setIgnoresCase (bool shouldIgnoreCase);
  9015. /** Returns a descriptive string containing the items.
  9016. This is handy for dumping the contents of an array.
  9017. */
  9018. String getDescription() const;
  9019. /** Reduces the amount of storage being used by the array.
  9020. Arrays typically allocate slightly more storage than they need, and after
  9021. removing elements, they may have quite a lot of unused space allocated.
  9022. This method will reduce the amount of allocated storage to a minimum.
  9023. */
  9024. void minimiseStorageOverheads();
  9025. private:
  9026. StringArray keys, values;
  9027. bool ignoreCase;
  9028. JUCE_LEAK_DETECTOR (StringPairArray);
  9029. };
  9030. #endif // __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  9031. /*** End of inlined file: juce_StringPairArray.h ***/
  9032. /*** Start of inlined file: juce_XmlElement.h ***/
  9033. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  9034. #define __JUCE_XMLELEMENT_JUCEHEADER__
  9035. /*** Start of inlined file: juce_File.h ***/
  9036. #ifndef __JUCE_FILE_JUCEHEADER__
  9037. #define __JUCE_FILE_JUCEHEADER__
  9038. /*** Start of inlined file: juce_Time.h ***/
  9039. #ifndef __JUCE_TIME_JUCEHEADER__
  9040. #define __JUCE_TIME_JUCEHEADER__
  9041. /*** Start of inlined file: juce_RelativeTime.h ***/
  9042. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  9043. #define __JUCE_RELATIVETIME_JUCEHEADER__
  9044. /** A relative measure of time.
  9045. The time is stored as a number of seconds, at double-precision floating
  9046. point accuracy, and may be positive or negative.
  9047. If you need an absolute time, (i.e. a date + time), see the Time class.
  9048. */
  9049. class JUCE_API RelativeTime
  9050. {
  9051. public:
  9052. /** Creates a RelativeTime.
  9053. @param seconds the number of seconds, which may be +ve or -ve.
  9054. @see milliseconds, minutes, hours, days, weeks
  9055. */
  9056. explicit RelativeTime (double seconds = 0.0) noexcept;
  9057. /** Copies another relative time. */
  9058. RelativeTime (const RelativeTime& other) noexcept;
  9059. /** Copies another relative time. */
  9060. RelativeTime& operator= (const RelativeTime& other) noexcept;
  9061. /** Destructor. */
  9062. ~RelativeTime() noexcept;
  9063. /** Creates a new RelativeTime object representing a number of milliseconds.
  9064. @see minutes, hours, days, weeks
  9065. */
  9066. static const RelativeTime milliseconds (int milliseconds) noexcept;
  9067. /** Creates a new RelativeTime object representing a number of milliseconds.
  9068. @see minutes, hours, days, weeks
  9069. */
  9070. static const RelativeTime milliseconds (int64 milliseconds) noexcept;
  9071. /** Creates a new RelativeTime object representing a number of minutes.
  9072. @see milliseconds, hours, days, weeks
  9073. */
  9074. static const RelativeTime minutes (double numberOfMinutes) noexcept;
  9075. /** Creates a new RelativeTime object representing a number of hours.
  9076. @see milliseconds, minutes, days, weeks
  9077. */
  9078. static const RelativeTime hours (double numberOfHours) noexcept;
  9079. /** Creates a new RelativeTime object representing a number of days.
  9080. @see milliseconds, minutes, hours, weeks
  9081. */
  9082. static const RelativeTime days (double numberOfDays) noexcept;
  9083. /** Creates a new RelativeTime object representing a number of weeks.
  9084. @see milliseconds, minutes, hours, days
  9085. */
  9086. static const RelativeTime weeks (double numberOfWeeks) noexcept;
  9087. /** Returns the number of milliseconds this time represents.
  9088. @see milliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  9089. */
  9090. int64 inMilliseconds() const noexcept;
  9091. /** Returns the number of seconds this time represents.
  9092. @see inMilliseconds, inMinutes, inHours, inDays, inWeeks
  9093. */
  9094. double inSeconds() const noexcept { return seconds; }
  9095. /** Returns the number of minutes this time represents.
  9096. @see inMilliseconds, inSeconds, inHours, inDays, inWeeks
  9097. */
  9098. double inMinutes() const noexcept;
  9099. /** Returns the number of hours this time represents.
  9100. @see inMilliseconds, inSeconds, inMinutes, inDays, inWeeks
  9101. */
  9102. double inHours() const noexcept;
  9103. /** Returns the number of days this time represents.
  9104. @see inMilliseconds, inSeconds, inMinutes, inHours, inWeeks
  9105. */
  9106. double inDays() const noexcept;
  9107. /** Returns the number of weeks this time represents.
  9108. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays
  9109. */
  9110. double inWeeks() const noexcept;
  9111. /** Returns a readable textual description of the time.
  9112. The exact format of the string returned will depend on
  9113. the magnitude of the time - e.g.
  9114. "1 min 4 secs", "1 hr 45 mins", "2 weeks 5 days", "140 ms"
  9115. so that only the two most significant units are printed.
  9116. The returnValueForZeroTime value is the result that is returned if the
  9117. length is zero. Depending on your application you might want to use this
  9118. to return something more relevant like "empty" or "0 secs", etc.
  9119. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  9120. */
  9121. String getDescription (const String& returnValueForZeroTime = "0") const;
  9122. /** Adds another RelativeTime to this one. */
  9123. const RelativeTime& operator+= (const RelativeTime& timeToAdd) noexcept;
  9124. /** Subtracts another RelativeTime from this one. */
  9125. const RelativeTime& operator-= (const RelativeTime& timeToSubtract) noexcept;
  9126. /** Adds a number of seconds to this time. */
  9127. const RelativeTime& operator+= (double secondsToAdd) noexcept;
  9128. /** Subtracts a number of seconds from this time. */
  9129. const RelativeTime& operator-= (double secondsToSubtract) noexcept;
  9130. private:
  9131. double seconds;
  9132. };
  9133. /** Compares two RelativeTimes. */
  9134. bool operator== (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9135. /** Compares two RelativeTimes. */
  9136. bool operator!= (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9137. /** Compares two RelativeTimes. */
  9138. bool operator> (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9139. /** Compares two RelativeTimes. */
  9140. bool operator< (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9141. /** Compares two RelativeTimes. */
  9142. bool operator>= (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9143. /** Compares two RelativeTimes. */
  9144. bool operator<= (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9145. /** Adds two RelativeTimes together. */
  9146. RelativeTime operator+ (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9147. /** Subtracts two RelativeTimes. */
  9148. RelativeTime operator- (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9149. #endif // __JUCE_RELATIVETIME_JUCEHEADER__
  9150. /*** End of inlined file: juce_RelativeTime.h ***/
  9151. /**
  9152. Holds an absolute date and time.
  9153. Internally, the time is stored at millisecond precision.
  9154. @see RelativeTime
  9155. */
  9156. class JUCE_API Time
  9157. {
  9158. public:
  9159. /** Creates a Time object.
  9160. This default constructor creates a time of 1st January 1970, (which is
  9161. represented internally as 0ms).
  9162. To create a time object representing the current time, use getCurrentTime().
  9163. @see getCurrentTime
  9164. */
  9165. Time() noexcept;
  9166. /** Creates a time based on a number of milliseconds.
  9167. The internal millisecond count is set to 0 (1st January 1970). To create a
  9168. time object set to the current time, use getCurrentTime().
  9169. @param millisecondsSinceEpoch the number of milliseconds since the unix
  9170. 'epoch' (midnight Jan 1st 1970).
  9171. @see getCurrentTime, currentTimeMillis
  9172. */
  9173. explicit Time (int64 millisecondsSinceEpoch) noexcept;
  9174. /** Creates a time from a set of date components.
  9175. The timezone is assumed to be whatever the system is using as its locale.
  9176. @param year the year, in 4-digit format, e.g. 2004
  9177. @param month the month, in the range 0 to 11
  9178. @param day the day of the month, in the range 1 to 31
  9179. @param hours hours in 24-hour clock format, 0 to 23
  9180. @param minutes minutes 0 to 59
  9181. @param seconds seconds 0 to 59
  9182. @param milliseconds milliseconds 0 to 999
  9183. @param useLocalTime if true, encode using the current machine's local time; if
  9184. false, it will always work in GMT.
  9185. */
  9186. Time (int year,
  9187. int month,
  9188. int day,
  9189. int hours,
  9190. int minutes,
  9191. int seconds = 0,
  9192. int milliseconds = 0,
  9193. bool useLocalTime = true) noexcept;
  9194. /** Creates a copy of another Time object. */
  9195. Time (const Time& other) noexcept;
  9196. /** Destructor. */
  9197. ~Time() noexcept;
  9198. /** Copies this time from another one. */
  9199. Time& operator= (const Time& other) noexcept;
  9200. /** Returns a Time object that is set to the current system time.
  9201. @see currentTimeMillis
  9202. */
  9203. static Time JUCE_CALLTYPE getCurrentTime() noexcept;
  9204. /** Returns the time as a number of milliseconds.
  9205. @returns the number of milliseconds this Time object represents, since
  9206. midnight jan 1st 1970.
  9207. @see getMilliseconds
  9208. */
  9209. int64 toMilliseconds() const noexcept { return millisSinceEpoch; }
  9210. /** Returns the year.
  9211. A 4-digit format is used, e.g. 2004.
  9212. */
  9213. int getYear() const noexcept;
  9214. /** Returns the number of the month.
  9215. The value returned is in the range 0 to 11.
  9216. @see getMonthName
  9217. */
  9218. int getMonth() const noexcept;
  9219. /** Returns the name of the month.
  9220. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  9221. it'll return the long form, e.g. "January"
  9222. @see getMonth
  9223. */
  9224. String getMonthName (bool threeLetterVersion) const;
  9225. /** Returns the day of the month.
  9226. The value returned is in the range 1 to 31.
  9227. */
  9228. int getDayOfMonth() const noexcept;
  9229. /** Returns the number of the day of the week.
  9230. The value returned is in the range 0 to 6 (0 = sunday, 1 = monday, etc).
  9231. */
  9232. int getDayOfWeek() const noexcept;
  9233. /** Returns the name of the weekday.
  9234. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  9235. false, it'll return the full version, e.g. "Tuesday".
  9236. */
  9237. String getWeekdayName (bool threeLetterVersion) const;
  9238. /** Returns the number of hours since midnight.
  9239. This is in 24-hour clock format, in the range 0 to 23.
  9240. @see getHoursInAmPmFormat, isAfternoon
  9241. */
  9242. int getHours() const noexcept;
  9243. /** Returns true if the time is in the afternoon.
  9244. So it returns true for "PM", false for "AM".
  9245. @see getHoursInAmPmFormat, getHours
  9246. */
  9247. bool isAfternoon() const noexcept;
  9248. /** Returns the hours in 12-hour clock format.
  9249. This will return a value 1 to 12 - use isAfternoon() to find out
  9250. whether this is in the afternoon or morning.
  9251. @see getHours, isAfternoon
  9252. */
  9253. int getHoursInAmPmFormat() const noexcept;
  9254. /** Returns the number of minutes, 0 to 59. */
  9255. int getMinutes() const noexcept;
  9256. /** Returns the number of seconds, 0 to 59. */
  9257. int getSeconds() const noexcept;
  9258. /** Returns the number of milliseconds, 0 to 999.
  9259. Unlike toMilliseconds(), this just returns the position within the
  9260. current second rather than the total number since the epoch.
  9261. @see toMilliseconds
  9262. */
  9263. int getMilliseconds() const noexcept;
  9264. /** Returns true if the local timezone uses a daylight saving correction. */
  9265. bool isDaylightSavingTime() const noexcept;
  9266. /** Returns a 3-character string to indicate the local timezone. */
  9267. String getTimeZone() const noexcept;
  9268. /** Quick way of getting a string version of a date and time.
  9269. For a more powerful way of formatting the date and time, see the formatted() method.
  9270. @param includeDate whether to include the date in the string
  9271. @param includeTime whether to include the time in the string
  9272. @param includeSeconds if the time is being included, this provides an option not to include
  9273. the seconds in it
  9274. @param use24HourClock if the time is being included, sets whether to use am/pm or 24
  9275. hour notation.
  9276. @see formatted
  9277. */
  9278. String toString (bool includeDate,
  9279. bool includeTime,
  9280. bool includeSeconds = true,
  9281. bool use24HourClock = false) const noexcept;
  9282. /** Converts this date/time to a string with a user-defined format.
  9283. This uses the C strftime() function to format this time as a string. To save you
  9284. looking it up, these are the escape codes that strftime uses (other codes might
  9285. work on some platforms and not others, but these are the common ones):
  9286. %a is replaced by the locale's abbreviated weekday name.
  9287. %A is replaced by the locale's full weekday name.
  9288. %b is replaced by the locale's abbreviated month name.
  9289. %B is replaced by the locale's full month name.
  9290. %c is replaced by the locale's appropriate date and time representation.
  9291. %d is replaced by the day of the month as a decimal number [01,31].
  9292. %H is replaced by the hour (24-hour clock) as a decimal number [00,23].
  9293. %I is replaced by the hour (12-hour clock) as a decimal number [01,12].
  9294. %j is replaced by the day of the year as a decimal number [001,366].
  9295. %m is replaced by the month as a decimal number [01,12].
  9296. %M is replaced by the minute as a decimal number [00,59].
  9297. %p is replaced by the locale's equivalent of either a.m. or p.m.
  9298. %S is replaced by the second as a decimal number [00,61].
  9299. %U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
  9300. %w is replaced by the weekday as a decimal number [0,6], with 0 representing Sunday.
  9301. %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.
  9302. %x is replaced by the locale's appropriate date representation.
  9303. %X is replaced by the locale's appropriate time representation.
  9304. %y is replaced by the year without century as a decimal number [00,99].
  9305. %Y is replaced by the year with century as a decimal number.
  9306. %Z is replaced by the timezone name or abbreviation, or by no bytes if no timezone information exists.
  9307. %% is replaced by %.
  9308. @see toString
  9309. */
  9310. String formatted (const String& format) const;
  9311. /** Adds a RelativeTime to this time. */
  9312. Time& operator+= (const RelativeTime& delta);
  9313. /** Subtracts a RelativeTime from this time. */
  9314. Time& operator-= (const RelativeTime& delta);
  9315. /** Tries to set the computer's clock.
  9316. @returns true if this succeeds, although depending on the system, the
  9317. application might not have sufficient privileges to do this.
  9318. */
  9319. bool setSystemTimeToThisTime() const;
  9320. /** Returns the name of a day of the week.
  9321. @param dayNumber the day, 0 to 6 (0 = sunday, 1 = monday, etc)
  9322. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  9323. false, it'll return the full version, e.g. "Tuesday".
  9324. */
  9325. static String getWeekdayName (int dayNumber,
  9326. bool threeLetterVersion);
  9327. /** Returns the name of one of the months.
  9328. @param monthNumber the month, 0 to 11
  9329. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  9330. it'll return the long form, e.g. "January"
  9331. */
  9332. static String getMonthName (int monthNumber,
  9333. bool threeLetterVersion);
  9334. // Static methods for getting system timers directly..
  9335. /** Returns the current system time.
  9336. Returns the number of milliseconds since midnight jan 1st 1970.
  9337. Should be accurate to within a few millisecs, depending on platform,
  9338. hardware, etc.
  9339. */
  9340. static int64 currentTimeMillis() noexcept;
  9341. /** Returns the number of millisecs since a fixed event (usually system startup).
  9342. This returns a monotonically increasing value which it unaffected by changes to the
  9343. system clock. It should be accurate to within a few millisecs, depending on platform,
  9344. hardware, etc.
  9345. Being a 32-bit return value, it will of course wrap back to 0 after 2^32 seconds of
  9346. uptime, so be careful to take that into account. If you need a 64-bit time, you can
  9347. use currentTimeMillis() instead.
  9348. @see getApproximateMillisecondCounter
  9349. */
  9350. static uint32 getMillisecondCounter() noexcept;
  9351. /** Returns the number of millisecs since a fixed event (usually system startup).
  9352. This has the same function as getMillisecondCounter(), but returns a more accurate
  9353. value, using a higher-resolution timer if one is available.
  9354. @see getMillisecondCounter
  9355. */
  9356. static double getMillisecondCounterHiRes() noexcept;
  9357. /** Waits until the getMillisecondCounter() reaches a given value.
  9358. This will make the thread sleep as efficiently as it can while it's waiting.
  9359. */
  9360. static void waitForMillisecondCounter (uint32 targetTime) noexcept;
  9361. /** Less-accurate but faster version of getMillisecondCounter().
  9362. This will return the last value that getMillisecondCounter() returned, so doesn't
  9363. need to make a system call, but is less accurate - it shouldn't be more than
  9364. 100ms away from the correct time, though, so is still accurate enough for a
  9365. lot of purposes.
  9366. @see getMillisecondCounter
  9367. */
  9368. static uint32 getApproximateMillisecondCounter() noexcept;
  9369. // High-resolution timers..
  9370. /** Returns the current high-resolution counter's tick-count.
  9371. This is a similar idea to getMillisecondCounter(), but with a higher
  9372. resolution.
  9373. @see getHighResolutionTicksPerSecond, highResolutionTicksToSeconds,
  9374. secondsToHighResolutionTicks
  9375. */
  9376. static int64 getHighResolutionTicks() noexcept;
  9377. /** Returns the resolution of the high-resolution counter in ticks per second.
  9378. @see getHighResolutionTicks, highResolutionTicksToSeconds,
  9379. secondsToHighResolutionTicks
  9380. */
  9381. static int64 getHighResolutionTicksPerSecond() noexcept;
  9382. /** Converts a number of high-resolution ticks into seconds.
  9383. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  9384. secondsToHighResolutionTicks
  9385. */
  9386. static double highResolutionTicksToSeconds (int64 ticks) noexcept;
  9387. /** Converts a number seconds into high-resolution ticks.
  9388. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  9389. highResolutionTicksToSeconds
  9390. */
  9391. static int64 secondsToHighResolutionTicks (double seconds) noexcept;
  9392. private:
  9393. int64 millisSinceEpoch;
  9394. };
  9395. /** Adds a RelativeTime to a Time. */
  9396. JUCE_API Time operator+ (const Time& time, const RelativeTime& delta);
  9397. /** Adds a RelativeTime to a Time. */
  9398. JUCE_API Time operator+ (const RelativeTime& delta, const Time& time);
  9399. /** Subtracts a RelativeTime from a Time. */
  9400. JUCE_API Time operator- (const Time& time, const RelativeTime& delta);
  9401. /** Returns the relative time difference between two times. */
  9402. JUCE_API const RelativeTime operator- (const Time& time1, const Time& time2);
  9403. /** Compares two Time objects. */
  9404. JUCE_API bool operator== (const Time& time1, const Time& time2);
  9405. /** Compares two Time objects. */
  9406. JUCE_API bool operator!= (const Time& time1, const Time& time2);
  9407. /** Compares two Time objects. */
  9408. JUCE_API bool operator< (const Time& time1, const Time& time2);
  9409. /** Compares two Time objects. */
  9410. JUCE_API bool operator<= (const Time& time1, const Time& time2);
  9411. /** Compares two Time objects. */
  9412. JUCE_API bool operator> (const Time& time1, const Time& time2);
  9413. /** Compares two Time objects. */
  9414. JUCE_API bool operator>= (const Time& time1, const Time& time2);
  9415. #endif // __JUCE_TIME_JUCEHEADER__
  9416. /*** End of inlined file: juce_Time.h ***/
  9417. /*** Start of inlined file: juce_MemoryBlock.h ***/
  9418. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  9419. #define __JUCE_MEMORYBLOCK_JUCEHEADER__
  9420. /**
  9421. A class to hold a resizable block of raw data.
  9422. */
  9423. class JUCE_API MemoryBlock
  9424. {
  9425. public:
  9426. /** Create an uninitialised block with 0 size. */
  9427. MemoryBlock() noexcept;
  9428. /** Creates a memory block with a given initial size.
  9429. @param initialSize the size of block to create
  9430. @param initialiseToZero whether to clear the memory or just leave it uninitialised
  9431. */
  9432. MemoryBlock (const size_t initialSize,
  9433. bool initialiseToZero = false);
  9434. /** Creates a copy of another memory block. */
  9435. MemoryBlock (const MemoryBlock& other);
  9436. /** Creates a memory block using a copy of a block of data.
  9437. @param dataToInitialiseFrom some data to copy into this block
  9438. @param sizeInBytes how much space to use
  9439. */
  9440. MemoryBlock (const void* dataToInitialiseFrom, size_t sizeInBytes);
  9441. /** Destructor. */
  9442. ~MemoryBlock() noexcept;
  9443. /** Copies another memory block onto this one.
  9444. This block will be resized and copied to exactly match the other one.
  9445. */
  9446. MemoryBlock& operator= (const MemoryBlock& other);
  9447. /** Compares two memory blocks.
  9448. @returns true only if the two blocks are the same size and have identical contents.
  9449. */
  9450. bool operator== (const MemoryBlock& other) const noexcept;
  9451. /** Compares two memory blocks.
  9452. @returns true if the two blocks are different sizes or have different contents.
  9453. */
  9454. bool operator!= (const MemoryBlock& other) const noexcept;
  9455. /** Returns true if the data in this MemoryBlock matches the raw bytes passed-in.
  9456. */
  9457. bool matches (const void* data, size_t dataSize) const noexcept;
  9458. /** Returns a void pointer to the data.
  9459. Note that the pointer returned will probably become invalid when the
  9460. block is resized.
  9461. */
  9462. void* getData() const noexcept { return data; }
  9463. /** Returns a byte from the memory block.
  9464. This returns a reference, so you can also use it to set a byte.
  9465. */
  9466. template <typename Type>
  9467. char& operator[] (const Type offset) const noexcept { return data [offset]; }
  9468. /** Returns the block's current allocated size, in bytes. */
  9469. size_t getSize() const noexcept { return size; }
  9470. /** Resizes the memory block.
  9471. This will try to keep as much of the block's current content as it can,
  9472. and can optionally be made to clear any new space that gets allocated at
  9473. the end of the block.
  9474. @param newSize the new desired size for the block
  9475. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  9476. whether to clear the new section or just leave it
  9477. uninitialised
  9478. @see ensureSize
  9479. */
  9480. void setSize (const size_t newSize,
  9481. bool initialiseNewSpaceToZero = false);
  9482. /** Increases the block's size only if it's smaller than a given size.
  9483. @param minimumSize if the block is already bigger than this size, no action
  9484. will be taken; otherwise it will be increased to this size
  9485. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  9486. whether to clear the new section or just leave it
  9487. uninitialised
  9488. @see setSize
  9489. */
  9490. void ensureSize (const size_t minimumSize,
  9491. bool initialiseNewSpaceToZero = false);
  9492. /** Fills the entire memory block with a repeated byte value.
  9493. This is handy for clearing a block of memory to zero.
  9494. */
  9495. void fillWith (uint8 valueToUse) noexcept;
  9496. /** Adds another block of data to the end of this one.
  9497. This block's size will be increased accordingly.
  9498. */
  9499. void append (const void* data, size_t numBytes);
  9500. /** Exchanges the contents of this and another memory block.
  9501. No actual copying is required for this, so it's very fast.
  9502. */
  9503. void swapWith (MemoryBlock& other) noexcept;
  9504. /** Copies data into this MemoryBlock from a memory address.
  9505. @param srcData the memory location of the data to copy into this block
  9506. @param destinationOffset the offset in this block at which the data being copied should begin
  9507. @param numBytes how much to copy in (if this goes beyond the size of the memory block,
  9508. it will be clipped so not to do anything nasty)
  9509. */
  9510. void copyFrom (const void* srcData,
  9511. int destinationOffset,
  9512. size_t numBytes) noexcept;
  9513. /** Copies data from this MemoryBlock to a memory address.
  9514. @param destData the memory location to write to
  9515. @param sourceOffset the offset within this block from which the copied data will be read
  9516. @param numBytes how much to copy (if this extends beyond the limits of the memory block,
  9517. zeros will be used for that portion of the data)
  9518. */
  9519. void copyTo (void* destData,
  9520. int sourceOffset,
  9521. size_t numBytes) const noexcept;
  9522. /** Chops out a section of the block.
  9523. This will remove a section of the memory block and close the gap around it,
  9524. shifting any subsequent data downwards and reducing the size of the block.
  9525. If the range specified goes beyond the size of the block, it will be clipped.
  9526. */
  9527. void removeSection (size_t startByte, size_t numBytesToRemove);
  9528. /** Attempts to parse the contents of the block as a zero-terminated UTF8 string. */
  9529. String toString() const;
  9530. /** Parses a string of hexadecimal numbers and writes this data into the memory block.
  9531. The block will be resized to the number of valid bytes read from the string.
  9532. Non-hex characters in the string will be ignored.
  9533. @see String::toHexString()
  9534. */
  9535. void loadFromHexString (const String& sourceHexString);
  9536. /** Sets a number of bits in the memory block, treating it as a long binary sequence. */
  9537. void setBitRange (size_t bitRangeStart,
  9538. size_t numBits,
  9539. int binaryNumberToApply) noexcept;
  9540. /** Reads a number of bits from the memory block, treating it as one long binary sequence */
  9541. int getBitRange (size_t bitRangeStart,
  9542. size_t numBitsToRead) const noexcept;
  9543. /** Returns a string of characters that represent the binary contents of this block.
  9544. Uses a 64-bit encoding system to allow binary data to be turned into a string
  9545. of simple non-extended characters, e.g. for storage in XML.
  9546. @see fromBase64Encoding
  9547. */
  9548. String toBase64Encoding() const;
  9549. /** Takes a string of encoded characters and turns it into binary data.
  9550. The string passed in must have been created by to64BitEncoding(), and this
  9551. block will be resized to recreate the original data block.
  9552. @see toBase64Encoding
  9553. */
  9554. bool fromBase64Encoding (const String& encodedString);
  9555. private:
  9556. HeapBlock <char> data;
  9557. size_t size;
  9558. static const char* const encodingTable;
  9559. JUCE_LEAK_DETECTOR (MemoryBlock);
  9560. };
  9561. #endif // __JUCE_MEMORYBLOCK_JUCEHEADER__
  9562. /*** End of inlined file: juce_MemoryBlock.h ***/
  9563. /*** Start of inlined file: juce_Result.h ***/
  9564. #ifndef __JUCE_RESULT_JUCEHEADER__
  9565. #define __JUCE_RESULT_JUCEHEADER__
  9566. /**
  9567. Represents the 'success' or 'failure' of an operation, and holds an associated
  9568. error message to describe the error when there's a failure.
  9569. E.g.
  9570. @code
  9571. Result myOperation()
  9572. {
  9573. if (doSomeKindOfFoobar())
  9574. return Result::ok();
  9575. else
  9576. return Result::fail ("foobar didn't work!");
  9577. }
  9578. const Result result (myOperation());
  9579. if (result.wasOk())
  9580. {
  9581. ...it's all good...
  9582. }
  9583. else
  9584. {
  9585. warnUserAboutFailure ("The foobar operation failed! Error message was: "
  9586. + result.getErrorMessage());
  9587. }
  9588. @endcode
  9589. */
  9590. class Result
  9591. {
  9592. public:
  9593. /** Creates and returns a 'successful' result. */
  9594. static Result ok() noexcept;
  9595. /** Creates a 'failure' result.
  9596. If you pass a blank error message in here, a default "Unknown Error" message
  9597. will be used instead.
  9598. */
  9599. static Result fail (const String& errorMessage) noexcept;
  9600. /** Returns true if this result indicates a success. */
  9601. bool wasOk() const noexcept;
  9602. /** Returns true if this result indicates a failure.
  9603. You can use getErrorMessage() to retrieve the error message associated
  9604. with the failure.
  9605. */
  9606. bool failed() const noexcept;
  9607. /** Returns true if this result indicates a success.
  9608. This is equivalent to calling wasOk().
  9609. */
  9610. operator bool() const noexcept;
  9611. /** Returns true if this result indicates a failure.
  9612. This is equivalent to calling failed().
  9613. */
  9614. bool operator!() const noexcept;
  9615. /** Returns the error message that was set when this result was created.
  9616. For a successful result, this will be an empty string;
  9617. */
  9618. const String& getErrorMessage() const noexcept;
  9619. Result (const Result& other);
  9620. Result& operator= (const Result& other);
  9621. bool operator== (const Result& other) const noexcept;
  9622. bool operator!= (const Result& other) const noexcept;
  9623. private:
  9624. String errorMessage;
  9625. explicit Result (const String& errorMessage) noexcept;
  9626. // These casts are private to prevent people trying to use the Result object in numeric contexts
  9627. operator int() const;
  9628. operator void*() const;
  9629. };
  9630. #endif // __JUCE_RESULT_JUCEHEADER__
  9631. /*** End of inlined file: juce_Result.h ***/
  9632. class FileInputStream;
  9633. class FileOutputStream;
  9634. /**
  9635. Represents a local file or directory.
  9636. This class encapsulates the absolute pathname of a file or directory, and
  9637. has methods for finding out about the file and changing its properties.
  9638. To read or write to the file, there are methods for returning an input or
  9639. output stream.
  9640. @see FileInputStream, FileOutputStream
  9641. */
  9642. class JUCE_API File
  9643. {
  9644. public:
  9645. /** Creates an (invalid) file object.
  9646. The file is initially set to an empty path, so getFullPath() will return
  9647. an empty string, and comparing the file to File::nonexistent will return
  9648. true.
  9649. You can use its operator= method to point it at a proper file.
  9650. */
  9651. File() {}
  9652. /** Creates a file from an absolute path.
  9653. If the path supplied is a relative path, it is taken to be relative
  9654. to the current working directory (see File::getCurrentWorkingDirectory()),
  9655. but this isn't a recommended way of creating a file, because you
  9656. never know what the CWD is going to be.
  9657. On the Mac/Linux, the path can include "~" notation for referring to
  9658. user home directories.
  9659. */
  9660. File (const String& path);
  9661. /** Creates a copy of another file object. */
  9662. File (const File& other);
  9663. /** Destructor. */
  9664. ~File() {}
  9665. /** Sets the file based on an absolute pathname.
  9666. If the path supplied is a relative path, it is taken to be relative
  9667. to the current working directory (see File::getCurrentWorkingDirectory()),
  9668. but this isn't a recommended way of creating a file, because you
  9669. never know what the CWD is going to be.
  9670. On the Mac/Linux, the path can include "~" notation for referring to
  9671. user home directories.
  9672. */
  9673. File& operator= (const String& newFilePath);
  9674. /** Copies from another file object. */
  9675. File& operator= (const File& otherFile);
  9676. /** This static constant is used for referring to an 'invalid' file. */
  9677. static const File nonexistent;
  9678. /** Checks whether the file actually exists.
  9679. @returns true if the file exists, either as a file or a directory.
  9680. @see existsAsFile, isDirectory
  9681. */
  9682. bool exists() const;
  9683. /** Checks whether the file exists and is a file rather than a directory.
  9684. @returns true only if this is a real file, false if it's a directory
  9685. or doesn't exist
  9686. @see exists, isDirectory
  9687. */
  9688. bool existsAsFile() const;
  9689. /** Checks whether the file is a directory that exists.
  9690. @returns true only if the file is a directory which actually exists, so
  9691. false if it's a file or doesn't exist at all
  9692. @see exists, existsAsFile
  9693. */
  9694. bool isDirectory() const;
  9695. /** Returns the size of the file in bytes.
  9696. @returns the number of bytes in the file, or 0 if it doesn't exist.
  9697. */
  9698. int64 getSize() const;
  9699. /** Utility function to convert a file size in bytes to a neat string description.
  9700. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  9701. 2000000 would produce "2 MB", etc.
  9702. */
  9703. static String descriptionOfSizeInBytes (int64 bytes);
  9704. /** Returns the complete, absolute path of this file.
  9705. This includes the filename and all its parent folders. On Windows it'll
  9706. also include the drive letter prefix; on Mac or Linux it'll be a complete
  9707. path starting from the root folder.
  9708. If you just want the file's name, you should use getFileName() or
  9709. getFileNameWithoutExtension().
  9710. @see getFileName, getRelativePathFrom
  9711. */
  9712. const String& getFullPathName() const noexcept { return fullPath; }
  9713. /** Returns the last section of the pathname.
  9714. Returns just the final part of the path - e.g. if the whole path
  9715. is "/moose/fish/foo.txt" this will return "foo.txt".
  9716. For a directory, it returns the final part of the path - e.g. for the
  9717. directory "/moose/fish" it'll return "fish".
  9718. If the filename begins with a dot, it'll return the whole filename, e.g. for
  9719. "/moose/.fish", it'll return ".fish"
  9720. @see getFullPathName, getFileNameWithoutExtension
  9721. */
  9722. String getFileName() const;
  9723. /** Creates a relative path that refers to a file relatively to a given directory.
  9724. e.g. File ("/moose/foo.txt").getRelativePathFrom (File ("/moose/fish/haddock"))
  9725. would return "../../foo.txt".
  9726. If it's not possible to navigate from one file to the other, an absolute
  9727. path is returned. If the paths are invalid, an empty string may also be
  9728. returned.
  9729. @param directoryToBeRelativeTo the directory which the resultant string will
  9730. be relative to. If this is actually a file rather than
  9731. a directory, its parent directory will be used instead.
  9732. If it doesn't exist, it's assumed to be a directory.
  9733. @see getChildFile, isAbsolutePath
  9734. */
  9735. String getRelativePathFrom (const File& directoryToBeRelativeTo) const;
  9736. /** Returns the file's extension.
  9737. Returns the file extension of this file, also including the dot.
  9738. e.g. "/moose/fish/foo.txt" would return ".txt"
  9739. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  9740. */
  9741. String getFileExtension() const;
  9742. /** Checks whether the file has a given extension.
  9743. @param extensionToTest the extension to look for - it doesn't matter whether or
  9744. not this string has a dot at the start, so ".wav" and "wav"
  9745. will have the same effect. The comparison used is
  9746. case-insensitve. To compare with multiple extensions, this
  9747. parameter can contain multiple strings, separated by semi-colons -
  9748. so, for example: hasFileExtension (".jpeg;png;gif") would return
  9749. true if the file has any of those three extensions.
  9750. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  9751. */
  9752. bool hasFileExtension (const String& extensionToTest) const;
  9753. /** Returns a version of this file with a different file extension.
  9754. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  9755. @param newExtension the new extension, either with or without a dot at the start (this
  9756. doesn't make any difference). To get remove a file's extension altogether,
  9757. pass an empty string into this function.
  9758. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  9759. */
  9760. File withFileExtension (const String& newExtension) const;
  9761. /** Returns the last part of the filename, without its file extension.
  9762. e.g. for "/moose/fish/foo.txt" this will return "foo".
  9763. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  9764. */
  9765. String getFileNameWithoutExtension() const;
  9766. /** Returns a 32-bit hash-code that identifies this file.
  9767. This is based on the filename. Obviously it's possible, although unlikely, that
  9768. two files will have the same hash-code.
  9769. */
  9770. int hashCode() const;
  9771. /** Returns a 64-bit hash-code that identifies this file.
  9772. This is based on the filename. Obviously it's possible, although unlikely, that
  9773. two files will have the same hash-code.
  9774. */
  9775. int64 hashCode64() const;
  9776. /** Returns a file based on a relative path.
  9777. This will find a child file or directory of the current object.
  9778. e.g.
  9779. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  9780. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  9781. If the string is actually an absolute path, it will be treated as such, e.g.
  9782. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  9783. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  9784. */
  9785. File getChildFile (String relativePath) const;
  9786. /** Returns a file which is in the same directory as this one.
  9787. This is equivalent to getParentDirectory().getChildFile (name).
  9788. @see getChildFile, getParentDirectory
  9789. */
  9790. File getSiblingFile (const String& siblingFileName) const;
  9791. /** Returns the directory that contains this file or directory.
  9792. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  9793. */
  9794. File getParentDirectory() const;
  9795. /** Checks whether a file is somewhere inside a directory.
  9796. Returns true if this file is somewhere inside a subdirectory of the directory
  9797. that is passed in. Neither file actually has to exist, because the function
  9798. just checks the paths for similarities.
  9799. e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
  9800. File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
  9801. */
  9802. bool isAChildOf (const File& potentialParentDirectory) const;
  9803. /** Chooses a filename relative to this one that doesn't already exist.
  9804. If this file is a directory, this will return a child file of this
  9805. directory that doesn't exist, by adding numbers to a prefix and suffix until
  9806. it finds one that isn't already there.
  9807. If the prefix + the suffix doesn't exist, it won't bother adding a number.
  9808. e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
  9809. return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
  9810. @param prefix the string to use for the filename before the number
  9811. @param suffix the string to add to the filename after the number
  9812. @param putNumbersInBrackets if true, this will create filenames in the
  9813. format "prefix(number)suffix", if false, it will leave the
  9814. brackets out.
  9815. */
  9816. File getNonexistentChildFile (const String& prefix,
  9817. const String& suffix,
  9818. bool putNumbersInBrackets = true) const;
  9819. /** Chooses a filename for a sibling file to this one that doesn't already exist.
  9820. If this file doesn't exist, this will just return itself, otherwise it
  9821. will return an appropriate sibling that doesn't exist, e.g. if a file
  9822. "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
  9823. @param putNumbersInBrackets whether to add brackets around the numbers that
  9824. get appended to the new filename.
  9825. */
  9826. File getNonexistentSibling (bool putNumbersInBrackets = true) const;
  9827. /** Compares the pathnames for two files. */
  9828. bool operator== (const File& otherFile) const;
  9829. /** Compares the pathnames for two files. */
  9830. bool operator!= (const File& otherFile) const;
  9831. /** Compares the pathnames for two files. */
  9832. bool operator< (const File& otherFile) const;
  9833. /** Compares the pathnames for two files. */
  9834. bool operator> (const File& otherFile) const;
  9835. /** Checks whether a file can be created or written to.
  9836. @returns true if it's possible to create and write to this file. If the file
  9837. doesn't already exist, this will check its parent directory to
  9838. see if writing is allowed.
  9839. @see setReadOnly
  9840. */
  9841. bool hasWriteAccess() const;
  9842. /** Changes the write-permission of a file or directory.
  9843. @param shouldBeReadOnly whether to add or remove write-permission
  9844. @param applyRecursively if the file is a directory and this is true, it will
  9845. recurse through all the subfolders changing the permissions
  9846. of all files
  9847. @returns true if it manages to change the file's permissions.
  9848. @see hasWriteAccess
  9849. */
  9850. bool setReadOnly (bool shouldBeReadOnly,
  9851. bool applyRecursively = false) const;
  9852. /** Returns true if this file is a hidden or system file.
  9853. The criteria for deciding whether a file is hidden are platform-dependent.
  9854. */
  9855. bool isHidden() const;
  9856. /** If this file is a link, this returns the file that it points to.
  9857. If this file isn't actually link, it'll just return itself.
  9858. */
  9859. File getLinkedTarget() const;
  9860. /** Returns the last modification time of this file.
  9861. @returns the time, or an invalid time if the file doesn't exist.
  9862. @see setLastModificationTime, getLastAccessTime, getCreationTime
  9863. */
  9864. Time getLastModificationTime() const;
  9865. /** Returns the last time this file was accessed.
  9866. @returns the time, or an invalid time if the file doesn't exist.
  9867. @see setLastAccessTime, getLastModificationTime, getCreationTime
  9868. */
  9869. Time getLastAccessTime() const;
  9870. /** Returns the time that this file was created.
  9871. @returns the time, or an invalid time if the file doesn't exist.
  9872. @see getLastModificationTime, getLastAccessTime
  9873. */
  9874. Time getCreationTime() const;
  9875. /** Changes the modification time for this file.
  9876. @param newTime the time to apply to the file
  9877. @returns true if it manages to change the file's time.
  9878. @see getLastModificationTime, setLastAccessTime, setCreationTime
  9879. */
  9880. bool setLastModificationTime (const Time& newTime) const;
  9881. /** Changes the last-access time for this file.
  9882. @param newTime the time to apply to the file
  9883. @returns true if it manages to change the file's time.
  9884. @see getLastAccessTime, setLastModificationTime, setCreationTime
  9885. */
  9886. bool setLastAccessTime (const Time& newTime) const;
  9887. /** Changes the creation date for this file.
  9888. @param newTime the time to apply to the file
  9889. @returns true if it manages to change the file's time.
  9890. @see getCreationTime, setLastModificationTime, setLastAccessTime
  9891. */
  9892. bool setCreationTime (const Time& newTime) const;
  9893. /** If possible, this will try to create a version string for the given file.
  9894. The OS may be able to look at the file and give a version for it - e.g. with
  9895. executables, bundles, dlls, etc. If no version is available, this will
  9896. return an empty string.
  9897. */
  9898. String getVersion() const;
  9899. /** Creates an empty file if it doesn't already exist.
  9900. If the file that this object refers to doesn't exist, this will create a file
  9901. of zero size.
  9902. If it already exists or is a directory, this method will do nothing.
  9903. @returns true if the file has been created (or if it already existed).
  9904. @see createDirectory
  9905. */
  9906. Result create() const;
  9907. /** Creates a new directory for this filename.
  9908. This will try to create the file as a directory, and fill also create
  9909. any parent directories it needs in order to complete the operation.
  9910. @returns a result to indicate whether the directory was created successfully, or
  9911. an error message if it failed.
  9912. @see create
  9913. */
  9914. Result createDirectory() const;
  9915. /** Deletes a file.
  9916. If this file is actually a directory, it may not be deleted correctly if it
  9917. contains files. See deleteRecursively() as a better way of deleting directories.
  9918. @returns true if the file has been successfully deleted (or if it didn't exist to
  9919. begin with).
  9920. @see deleteRecursively
  9921. */
  9922. bool deleteFile() const;
  9923. /** Deletes a file or directory and all its subdirectories.
  9924. If this file is a directory, this will try to delete it and all its subfolders. If
  9925. it's just a file, it will just try to delete the file.
  9926. @returns true if the file and all its subfolders have been successfully deleted
  9927. (or if it didn't exist to begin with).
  9928. @see deleteFile
  9929. */
  9930. bool deleteRecursively() const;
  9931. /** Moves this file or folder to the trash.
  9932. @returns true if the operation succeeded. It could fail if the trash is full, or
  9933. if the file is write-protected, so you should check the return value
  9934. and act appropriately.
  9935. */
  9936. bool moveToTrash() const;
  9937. /** Moves or renames a file.
  9938. Tries to move a file to a different location.
  9939. If the target file already exists, this will attempt to delete it first, and
  9940. will fail if this can't be done.
  9941. Note that the destination file isn't the directory to put it in, it's the actual
  9942. filename that you want the new file to have.
  9943. @returns true if the operation succeeds
  9944. */
  9945. bool moveFileTo (const File& targetLocation) const;
  9946. /** Copies a file.
  9947. Tries to copy a file to a different location.
  9948. If the target file already exists, this will attempt to delete it first, and
  9949. will fail if this can't be done.
  9950. @returns true if the operation succeeds
  9951. */
  9952. bool copyFileTo (const File& targetLocation) const;
  9953. /** Copies a directory.
  9954. Tries to copy an entire directory, recursively.
  9955. If this file isn't a directory or if any target files can't be created, this
  9956. will return false.
  9957. @param newDirectory the directory that this one should be copied to. Note that this
  9958. is the name of the actual directory to create, not the directory
  9959. into which the new one should be placed, so there must be enough
  9960. write privileges to create it if it doesn't exist. Any files inside
  9961. it will be overwritten by similarly named ones that are copied.
  9962. */
  9963. bool copyDirectoryTo (const File& newDirectory) const;
  9964. /** Used in file searching, to specify whether to return files, directories, or both.
  9965. */
  9966. enum TypesOfFileToFind
  9967. {
  9968. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  9969. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  9970. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  9971. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  9972. };
  9973. /** Searches inside a directory for files matching a wildcard pattern.
  9974. Assuming that this file is a directory, this method will search it
  9975. for either files or subdirectories whose names match a filename pattern.
  9976. @param results an array to which File objects will be added for the
  9977. files that the search comes up with
  9978. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  9979. return files, directories, or both. If the ignoreHiddenFiles flag
  9980. is also added to this value, hidden files won't be returned
  9981. @param searchRecursively if true, all subdirectories will be recursed into to do
  9982. an exhaustive search
  9983. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  9984. @returns the number of results that have been found
  9985. @see getNumberOfChildFiles, DirectoryIterator
  9986. */
  9987. int findChildFiles (Array<File>& results,
  9988. int whatToLookFor,
  9989. bool searchRecursively,
  9990. const String& wildCardPattern = "*") const;
  9991. /** Searches inside a directory and counts how many files match a wildcard pattern.
  9992. Assuming that this file is a directory, this method will search it
  9993. for either files or subdirectories whose names match a filename pattern,
  9994. and will return the number of matches found.
  9995. This isn't a recursive call, and will only search this directory, not
  9996. its children.
  9997. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  9998. count files, directories, or both. If the ignoreHiddenFiles flag
  9999. is also added to this value, hidden files won't be counted
  10000. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  10001. @returns the number of matches found
  10002. @see findChildFiles, DirectoryIterator
  10003. */
  10004. int getNumberOfChildFiles (int whatToLookFor,
  10005. const String& wildCardPattern = "*") const;
  10006. /** Returns true if this file is a directory that contains one or more subdirectories.
  10007. @see isDirectory, findChildFiles
  10008. */
  10009. bool containsSubDirectories() const;
  10010. /** Creates a stream to read from this file.
  10011. @returns a stream that will read from this file (initially positioned at the
  10012. start of the file), or 0 if the file can't be opened for some reason
  10013. @see createOutputStream, loadFileAsData
  10014. */
  10015. FileInputStream* createInputStream() const;
  10016. /** Creates a stream to write to this file.
  10017. If the file exists, the stream that is returned will be positioned ready for
  10018. writing at the end of the file, so you might want to use deleteFile() first
  10019. to write to an empty file.
  10020. @returns a stream that will write to this file (initially positioned at the
  10021. end of the file), or 0 if the file can't be opened for some reason
  10022. @see createInputStream, appendData, appendText
  10023. */
  10024. FileOutputStream* createOutputStream (int bufferSize = 0x8000) const;
  10025. /** Loads a file's contents into memory as a block of binary data.
  10026. Of course, trying to load a very large file into memory will blow up, so
  10027. it's better to check first.
  10028. @param result the data block to which the file's contents should be appended - note
  10029. that if the memory block might already contain some data, you
  10030. might want to clear it first
  10031. @returns true if the file could all be read into memory
  10032. */
  10033. bool loadFileAsData (MemoryBlock& result) const;
  10034. /** Reads a file into memory as a string.
  10035. Attempts to load the entire file as a zero-terminated string.
  10036. This makes use of InputStream::readEntireStreamAsString, which should
  10037. automatically cope with unicode/acsii file formats.
  10038. */
  10039. String loadFileAsString() const;
  10040. /** Appends a block of binary data to the end of the file.
  10041. This will try to write the given buffer to the end of the file.
  10042. @returns false if it can't write to the file for some reason
  10043. */
  10044. bool appendData (const void* dataToAppend,
  10045. int numberOfBytes) const;
  10046. /** Replaces this file's contents with a given block of data.
  10047. This will delete the file and replace it with the given data.
  10048. A nice feature of this method is that it's safe - instead of deleting
  10049. the file first and then re-writing it, it creates a new temporary file,
  10050. writes the data to that, and then moves the new file to replace the existing
  10051. file. This means that if the power gets pulled out or something crashes,
  10052. you're a lot less likely to end up with a corrupted or unfinished file..
  10053. Returns true if the operation succeeds, or false if it fails.
  10054. @see appendText
  10055. */
  10056. bool replaceWithData (const void* dataToWrite,
  10057. int numberOfBytes) const;
  10058. /** Appends a string to the end of the file.
  10059. This will try to append a text string to the file, as either 16-bit unicode
  10060. or 8-bit characters in the default system encoding.
  10061. It can also write the 'ff fe' unicode header bytes before the text to indicate
  10062. the endianness of the file.
  10063. Any single \\n characters in the string are replaced with \\r\\n before it is written.
  10064. @see replaceWithText
  10065. */
  10066. bool appendText (const String& textToAppend,
  10067. bool asUnicode = false,
  10068. bool writeUnicodeHeaderBytes = false) const;
  10069. /** Replaces this file's contents with a given text string.
  10070. This will delete the file and replace it with the given text.
  10071. A nice feature of this method is that it's safe - instead of deleting
  10072. the file first and then re-writing it, it creates a new temporary file,
  10073. writes the text to that, and then moves the new file to replace the existing
  10074. file. This means that if the power gets pulled out or something crashes,
  10075. you're a lot less likely to end up with an empty file..
  10076. For an explanation of the parameters here, see the appendText() method.
  10077. Returns true if the operation succeeds, or false if it fails.
  10078. @see appendText
  10079. */
  10080. bool replaceWithText (const String& textToWrite,
  10081. bool asUnicode = false,
  10082. bool writeUnicodeHeaderBytes = false) const;
  10083. /** Attempts to scan the contents of this file and compare it to another file, returning
  10084. true if this is possible and they match byte-for-byte.
  10085. */
  10086. bool hasIdenticalContentTo (const File& other) const;
  10087. /** Creates a set of files to represent each file root.
  10088. e.g. on Windows this will create files for "c:\", "d:\" etc according
  10089. to which ones are available. On the Mac/Linux, this will probably
  10090. just add a single entry for "/".
  10091. */
  10092. static void findFileSystemRoots (Array<File>& results);
  10093. /** Finds the name of the drive on which this file lives.
  10094. @returns the volume label of the drive, or an empty string if this isn't possible
  10095. */
  10096. String getVolumeLabel() const;
  10097. /** Returns the serial number of the volume on which this file lives.
  10098. @returns the serial number, or zero if there's a problem doing this
  10099. */
  10100. int getVolumeSerialNumber() const;
  10101. /** Returns the number of bytes free on the drive that this file lives on.
  10102. @returns the number of bytes free, or 0 if there's a problem finding this out
  10103. @see getVolumeTotalSize
  10104. */
  10105. int64 getBytesFreeOnVolume() const;
  10106. /** Returns the total size of the drive that contains this file.
  10107. @returns the total number of bytes that the volume can hold
  10108. @see getBytesFreeOnVolume
  10109. */
  10110. int64 getVolumeTotalSize() const;
  10111. /** Returns true if this file is on a CD or DVD drive. */
  10112. bool isOnCDRomDrive() const;
  10113. /** Returns true if this file is on a hard disk.
  10114. This will fail if it's a network drive, but will still be true for
  10115. removable hard-disks.
  10116. */
  10117. bool isOnHardDisk() const;
  10118. /** Returns true if this file is on a removable disk drive.
  10119. This might be a usb-drive, a CD-rom, or maybe a network drive.
  10120. */
  10121. bool isOnRemovableDrive() const;
  10122. /** Launches the file as a process.
  10123. - if the file is executable, this will run it.
  10124. - if it's a document of some kind, it will launch the document with its
  10125. default viewer application.
  10126. - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
  10127. @see revealToUser
  10128. */
  10129. bool startAsProcess (const String& parameters = String::empty) const;
  10130. /** Opens Finder, Explorer, or whatever the OS uses, to show the user this file's location.
  10131. @see startAsProcess
  10132. */
  10133. void revealToUser() const;
  10134. /** A set of types of location that can be passed to the getSpecialLocation() method.
  10135. */
  10136. enum SpecialLocationType
  10137. {
  10138. /** The user's home folder. This is the same as using File ("~"). */
  10139. userHomeDirectory,
  10140. /** The user's default documents folder. On Windows, this might be the user's
  10141. "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
  10142. doesn't tend to have one of these, so it might just return their home folder.
  10143. */
  10144. userDocumentsDirectory,
  10145. /** The folder that contains the user's desktop objects. */
  10146. userDesktopDirectory,
  10147. /** The folder in which applications store their persistent user-specific settings.
  10148. On Windows, this might be "\Documents and Settings\username\Application Data".
  10149. On the Mac, it might be "~/Library". If you're going to store your settings in here,
  10150. always create your own sub-folder to put them in, to avoid making a mess.
  10151. */
  10152. userApplicationDataDirectory,
  10153. /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
  10154. of the computer, rather than just the current user.
  10155. On the Mac it'll be "/Library", on Windows, it could be something like
  10156. "\Documents and Settings\All Users\Application Data".
  10157. Depending on the setup, this folder may be read-only.
  10158. */
  10159. commonApplicationDataDirectory,
  10160. /** The folder that should be used for temporary files.
  10161. Always delete them when you're finished, to keep the user's computer tidy!
  10162. */
  10163. tempDirectory,
  10164. /** Returns this application's executable file.
  10165. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  10166. host app.
  10167. On the mac this will return the unix binary, not the package folder - see
  10168. currentApplicationFile for that.
  10169. See also invokedExecutableFile, which is similar, but if the exe was launched from a
  10170. file link, invokedExecutableFile will return the name of the link.
  10171. */
  10172. currentExecutableFile,
  10173. /** Returns this application's location.
  10174. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  10175. host app.
  10176. On the mac this will return the package folder (if it's in one), not the unix binary
  10177. that's inside it - compare with currentExecutableFile.
  10178. */
  10179. currentApplicationFile,
  10180. /** Returns the file that was invoked to launch this executable.
  10181. This may differ from currentExecutableFile if the app was started from e.g. a link - this
  10182. will return the name of the link that was used, whereas currentExecutableFile will return
  10183. the actual location of the target executable.
  10184. */
  10185. invokedExecutableFile,
  10186. /** In a plugin, this will return the path of the host executable. */
  10187. hostApplicationPath,
  10188. /** The directory in which applications normally get installed.
  10189. So on windows, this would be something like "c:\program files", on the
  10190. Mac "/Applications", or "/usr" on linux.
  10191. */
  10192. globalApplicationsDirectory,
  10193. /** The most likely place where a user might store their music files.
  10194. */
  10195. userMusicDirectory,
  10196. /** The most likely place where a user might store their movie files.
  10197. */
  10198. userMoviesDirectory,
  10199. };
  10200. /** Finds the location of a special type of file or directory, such as a home folder or
  10201. documents folder.
  10202. @see SpecialLocationType
  10203. */
  10204. static File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
  10205. /** Returns a temporary file in the system's temp directory.
  10206. This will try to return the name of a non-existent temp file.
  10207. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  10208. */
  10209. static File createTempFile (const String& fileNameEnding);
  10210. /** Returns the current working directory.
  10211. @see setAsCurrentWorkingDirectory
  10212. */
  10213. static File getCurrentWorkingDirectory();
  10214. /** Sets the current working directory to be this file.
  10215. For this to work the file must point to a valid directory.
  10216. @returns true if the current directory has been changed.
  10217. @see getCurrentWorkingDirectory
  10218. */
  10219. bool setAsCurrentWorkingDirectory() const;
  10220. /** The system-specific file separator character.
  10221. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  10222. */
  10223. static const juce_wchar separator;
  10224. /** The system-specific file separator character, as a string.
  10225. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  10226. */
  10227. static const String separatorString;
  10228. /** Removes illegal characters from a filename.
  10229. This will return a copy of the given string after removing characters
  10230. that are not allowed in a legal filename, and possibly shortening the
  10231. string if it's too long.
  10232. Because this will remove slashes, don't use it on an absolute pathname.
  10233. @see createLegalPathName
  10234. */
  10235. static String createLegalFileName (const String& fileNameToFix);
  10236. /** Removes illegal characters from a pathname.
  10237. Similar to createLegalFileName(), but this won't remove slashes, so can
  10238. be used on a complete pathname.
  10239. @see createLegalFileName
  10240. */
  10241. static String createLegalPathName (const String& pathNameToFix);
  10242. /** Indicates whether filenames are case-sensitive on the current operating system.
  10243. */
  10244. static bool areFileNamesCaseSensitive();
  10245. /** Returns true if the string seems to be a fully-specified absolute path.
  10246. */
  10247. static bool isAbsolutePath (const String& path);
  10248. /** Creates a file that simply contains this string, without doing the sanity-checking
  10249. that the normal constructors do.
  10250. Best to avoid this unless you really know what you're doing.
  10251. */
  10252. static File createFileWithoutCheckingPath (const String& path);
  10253. /** Adds a separator character to the end of a path if it doesn't already have one. */
  10254. static String addTrailingSeparator (const String& path);
  10255. #if JUCE_MAC || JUCE_IOS || DOXYGEN
  10256. /** OSX ONLY - Finds the OSType of a file from the its resources. */
  10257. OSType getMacOSType() const;
  10258. /** OSX ONLY - Returns true if this file is actually a bundle. */
  10259. bool isBundle() const;
  10260. #endif
  10261. #if JUCE_MAC || DOXYGEN
  10262. /** OSX ONLY - Adds this file to the OSX dock */
  10263. void addToDock() const;
  10264. #endif
  10265. private:
  10266. String fullPath;
  10267. // internal way of contructing a file without checking the path
  10268. friend class DirectoryIterator;
  10269. File (const String&, int);
  10270. String getPathUpToLastSlash() const;
  10271. Result createDirectoryInternal (const String& fileName) const;
  10272. bool copyInternal (const File& dest) const;
  10273. bool moveInternal (const File& dest) const;
  10274. bool setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const;
  10275. void getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const;
  10276. bool setFileReadOnlyInternal (bool shouldBeReadOnly) const;
  10277. static String parseAbsolutePath (const String& path);
  10278. JUCE_LEAK_DETECTOR (File);
  10279. };
  10280. #endif // __JUCE_FILE_JUCEHEADER__
  10281. /*** End of inlined file: juce_File.h ***/
  10282. /** A handy macro to make it easy to iterate all the child elements in an XmlElement.
  10283. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  10284. will be the name of a pointer to each child element.
  10285. E.g. @code
  10286. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  10287. forEachXmlChildElement (*myParentXml, child)
  10288. {
  10289. if (child->hasTagName ("FOO"))
  10290. doSomethingWithXmlElement (child);
  10291. }
  10292. @endcode
  10293. @see forEachXmlChildElementWithTagName
  10294. */
  10295. #define forEachXmlChildElement(parentXmlElement, childElementVariableName) \
  10296. \
  10297. for (JUCE_NAMESPACE::XmlElement* childElementVariableName = (parentXmlElement).getFirstChildElement(); \
  10298. childElementVariableName != 0; \
  10299. childElementVariableName = childElementVariableName->getNextElement())
  10300. /** A macro that makes it easy to iterate all the child elements of an XmlElement
  10301. which have a specified tag.
  10302. This does the same job as the forEachXmlChildElement macro, but only for those
  10303. elements that have a particular tag name.
  10304. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  10305. will be the name of a pointer to each child element. The requiredTagName is the
  10306. tag name to match.
  10307. E.g. @code
  10308. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  10309. forEachXmlChildElementWithTagName (*myParentXml, child, "MYTAG")
  10310. {
  10311. // the child object is now guaranteed to be a <MYTAG> element..
  10312. doSomethingWithMYTAGElement (child);
  10313. }
  10314. @endcode
  10315. @see forEachXmlChildElement
  10316. */
  10317. #define forEachXmlChildElementWithTagName(parentXmlElement, childElementVariableName, requiredTagName) \
  10318. \
  10319. for (JUCE_NAMESPACE::XmlElement* childElementVariableName = (parentXmlElement).getChildByName (requiredTagName); \
  10320. childElementVariableName != 0; \
  10321. childElementVariableName = childElementVariableName->getNextElementWithTagName (requiredTagName))
  10322. /** Used to build a tree of elements representing an XML document.
  10323. An XML document can be parsed into a tree of XmlElements, each of which
  10324. represents an XML tag structure, and which may itself contain other
  10325. nested elements.
  10326. An XmlElement can also be converted back into a text document, and has
  10327. lots of useful methods for manipulating its attributes and sub-elements,
  10328. so XmlElements can actually be used as a handy general-purpose data
  10329. structure.
  10330. Here's an example of parsing some elements: @code
  10331. // check we're looking at the right kind of document..
  10332. if (myElement->hasTagName ("ANIMALS"))
  10333. {
  10334. // now we'll iterate its sub-elements looking for 'giraffe' elements..
  10335. forEachXmlChildElement (*myElement, e)
  10336. {
  10337. if (e->hasTagName ("GIRAFFE"))
  10338. {
  10339. // found a giraffe, so use some of its attributes..
  10340. String giraffeName = e->getStringAttribute ("name");
  10341. int giraffeAge = e->getIntAttribute ("age");
  10342. bool isFriendly = e->getBoolAttribute ("friendly");
  10343. }
  10344. }
  10345. }
  10346. @endcode
  10347. And here's an example of how to create an XML document from scratch: @code
  10348. // create an outer node called "ANIMALS"
  10349. XmlElement animalsList ("ANIMALS");
  10350. for (int i = 0; i < numAnimals; ++i)
  10351. {
  10352. // create an inner element..
  10353. XmlElement* giraffe = new XmlElement ("GIRAFFE");
  10354. giraffe->setAttribute ("name", "nigel");
  10355. giraffe->setAttribute ("age", 10);
  10356. giraffe->setAttribute ("friendly", true);
  10357. // ..and add our new element to the parent node
  10358. animalsList.addChildElement (giraffe);
  10359. }
  10360. // now we can turn the whole thing into a text document..
  10361. String myXmlDoc = animalsList.createDocument (String::empty);
  10362. @endcode
  10363. @see XmlDocument
  10364. */
  10365. class JUCE_API XmlElement
  10366. {
  10367. public:
  10368. /** Creates an XmlElement with this tag name. */
  10369. explicit XmlElement (const String& tagName) noexcept;
  10370. /** Creates a (deep) copy of another element. */
  10371. XmlElement (const XmlElement& other);
  10372. /** Creates a (deep) copy of another element. */
  10373. XmlElement& operator= (const XmlElement& other);
  10374. /** Deleting an XmlElement will also delete all its child elements. */
  10375. ~XmlElement() noexcept;
  10376. /** Compares two XmlElements to see if they contain the same text and attiributes.
  10377. The elements are only considered equivalent if they contain the same attiributes
  10378. with the same values, and have the same sub-nodes.
  10379. @param other the other element to compare to
  10380. @param ignoreOrderOfAttributes if true, this means that two elements with the
  10381. same attributes in a different order will be
  10382. considered the same; if false, the attributes must
  10383. be in the same order as well
  10384. */
  10385. bool isEquivalentTo (const XmlElement* other,
  10386. bool ignoreOrderOfAttributes) const noexcept;
  10387. /** Returns an XML text document that represents this element.
  10388. The string returned can be parsed to recreate the same XmlElement that
  10389. was used to create it.
  10390. @param dtdToUse the DTD to add to the document
  10391. @param allOnOneLine if true, this means that the document will not contain any
  10392. linefeeds, so it'll be smaller but not very easy to read.
  10393. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  10394. document
  10395. @param encodingType the character encoding format string to put into the xml
  10396. header
  10397. @param lineWrapLength the line length that will be used before items get placed on
  10398. a new line. This isn't an absolute maximum length, it just
  10399. determines how lists of attributes get broken up
  10400. @see writeToStream, writeToFile
  10401. */
  10402. String createDocument (const String& dtdToUse,
  10403. bool allOnOneLine = false,
  10404. bool includeXmlHeader = true,
  10405. const String& encodingType = "UTF-8",
  10406. int lineWrapLength = 60) const;
  10407. /** Writes the document to a stream as UTF-8.
  10408. @param output the stream to write to
  10409. @param dtdToUse the DTD to add to the document
  10410. @param allOnOneLine if true, this means that the document will not contain any
  10411. linefeeds, so it'll be smaller but not very easy to read.
  10412. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  10413. document
  10414. @param encodingType the character encoding format string to put into the xml
  10415. header
  10416. @param lineWrapLength the line length that will be used before items get placed on
  10417. a new line. This isn't an absolute maximum length, it just
  10418. determines how lists of attributes get broken up
  10419. @see writeToFile, createDocument
  10420. */
  10421. void writeToStream (OutputStream& output,
  10422. const String& dtdToUse,
  10423. bool allOnOneLine = false,
  10424. bool includeXmlHeader = true,
  10425. const String& encodingType = "UTF-8",
  10426. int lineWrapLength = 60) const;
  10427. /** Writes the element to a file as an XML document.
  10428. To improve safety in case something goes wrong while writing the file, this
  10429. will actually write the document to a new temporary file in the same
  10430. directory as the destination file, and if this succeeds, it will rename this
  10431. new file as the destination file (overwriting any existing file that was there).
  10432. @param destinationFile the file to write to. If this already exists, it will be
  10433. overwritten.
  10434. @param dtdToUse the DTD to add to the document
  10435. @param encodingType the character encoding format string to put into the xml
  10436. header
  10437. @param lineWrapLength the line length that will be used before items get placed on
  10438. a new line. This isn't an absolute maximum length, it just
  10439. determines how lists of attributes get broken up
  10440. @returns true if the file is written successfully; false if something goes wrong
  10441. in the process
  10442. @see createDocument
  10443. */
  10444. bool writeToFile (const File& destinationFile,
  10445. const String& dtdToUse,
  10446. const String& encodingType = "UTF-8",
  10447. int lineWrapLength = 60) const;
  10448. /** Returns this element's tag type name.
  10449. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would return
  10450. "MOOSE".
  10451. @see hasTagName
  10452. */
  10453. inline const String& getTagName() const noexcept { return tagName; }
  10454. /** Tests whether this element has a particular tag name.
  10455. @param possibleTagName the tag name you're comparing it with
  10456. @see getTagName
  10457. */
  10458. bool hasTagName (const String& possibleTagName) const noexcept;
  10459. /** Returns the number of XML attributes this element contains.
  10460. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would
  10461. return 2.
  10462. */
  10463. int getNumAttributes() const noexcept;
  10464. /** Returns the name of one of the elements attributes.
  10465. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  10466. getAttributeName(1) would return "antlers".
  10467. @see getAttributeValue, getStringAttribute
  10468. */
  10469. const String& getAttributeName (int attributeIndex) const noexcept;
  10470. /** Returns the value of one of the elements attributes.
  10471. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  10472. getAttributeName(1) would return "2".
  10473. @see getAttributeName, getStringAttribute
  10474. */
  10475. const String& getAttributeValue (int attributeIndex) const noexcept;
  10476. // Attribute-handling methods..
  10477. /** Checks whether the element contains an attribute with a certain name. */
  10478. bool hasAttribute (const String& attributeName) const noexcept;
  10479. /** Returns the value of a named attribute.
  10480. @param attributeName the name of the attribute to look up
  10481. */
  10482. const String& getStringAttribute (const String& attributeName) const noexcept;
  10483. /** Returns the value of a named attribute.
  10484. @param attributeName the name of the attribute to look up
  10485. @param defaultReturnValue a value to return if the element doesn't have an attribute
  10486. with this name
  10487. */
  10488. String getStringAttribute (const String& attributeName,
  10489. const String& defaultReturnValue) const;
  10490. /** Compares the value of a named attribute with a value passed-in.
  10491. @param attributeName the name of the attribute to look up
  10492. @param stringToCompareAgainst the value to compare it with
  10493. @param ignoreCase whether the comparison should be case-insensitive
  10494. @returns true if the value of the attribute is the same as the string passed-in;
  10495. false if it's different (or if no such attribute exists)
  10496. */
  10497. bool compareAttribute (const String& attributeName,
  10498. const String& stringToCompareAgainst,
  10499. bool ignoreCase = false) const noexcept;
  10500. /** Returns the value of a named attribute as an integer.
  10501. This will try to find the attribute and convert it to an integer (using
  10502. the String::getIntValue() method).
  10503. @param attributeName the name of the attribute to look up
  10504. @param defaultReturnValue a value to return if the element doesn't have an attribute
  10505. with this name
  10506. @see setAttribute
  10507. */
  10508. int getIntAttribute (const String& attributeName,
  10509. int defaultReturnValue = 0) const;
  10510. /** Returns the value of a named attribute as floating-point.
  10511. This will try to find the attribute and convert it to an integer (using
  10512. the String::getDoubleValue() method).
  10513. @param attributeName the name of the attribute to look up
  10514. @param defaultReturnValue a value to return if the element doesn't have an attribute
  10515. with this name
  10516. @see setAttribute
  10517. */
  10518. double getDoubleAttribute (const String& attributeName,
  10519. double defaultReturnValue = 0.0) const;
  10520. /** Returns the value of a named attribute as a boolean.
  10521. This will try to find the attribute and interpret it as a boolean. To do this,
  10522. it'll return true if the value is "1", "true", "y", etc, or false for other
  10523. values.
  10524. @param attributeName the name of the attribute to look up
  10525. @param defaultReturnValue a value to return if the element doesn't have an attribute
  10526. with this name
  10527. */
  10528. bool getBoolAttribute (const String& attributeName,
  10529. bool defaultReturnValue = false) const;
  10530. /** Adds a named attribute to the element.
  10531. If the element already contains an attribute with this name, it's value will
  10532. be updated to the new value. If there's no such attribute yet, a new one will
  10533. be added.
  10534. Note that there are other setAttribute() methods that take integers,
  10535. doubles, etc. to make it easy to store numbers.
  10536. @param attributeName the name of the attribute to set
  10537. @param newValue the value to set it to
  10538. @see removeAttribute
  10539. */
  10540. void setAttribute (const String& attributeName,
  10541. const String& newValue);
  10542. /** Adds a named attribute to the element, setting it to an integer value.
  10543. If the element already contains an attribute with this name, it's value will
  10544. be updated to the new value. If there's no such attribute yet, a new one will
  10545. be added.
  10546. Note that there are other setAttribute() methods that take integers,
  10547. doubles, etc. to make it easy to store numbers.
  10548. @param attributeName the name of the attribute to set
  10549. @param newValue the value to set it to
  10550. */
  10551. void setAttribute (const String& attributeName,
  10552. int newValue);
  10553. /** Adds a named attribute to the element, setting it to a floating-point value.
  10554. If the element already contains an attribute with this name, it's value will
  10555. be updated to the new value. If there's no such attribute yet, a new one will
  10556. be added.
  10557. Note that there are other setAttribute() methods that take integers,
  10558. doubles, etc. to make it easy to store numbers.
  10559. @param attributeName the name of the attribute to set
  10560. @param newValue the value to set it to
  10561. */
  10562. void setAttribute (const String& attributeName,
  10563. double newValue);
  10564. /** Removes a named attribute from the element.
  10565. @param attributeName the name of the attribute to remove
  10566. @see removeAllAttributes
  10567. */
  10568. void removeAttribute (const String& attributeName) noexcept;
  10569. /** Removes all attributes from this element.
  10570. */
  10571. void removeAllAttributes() noexcept;
  10572. // Child element methods..
  10573. /** Returns the first of this element's sub-elements.
  10574. see getNextElement() for an example of how to iterate the sub-elements.
  10575. @see forEachXmlChildElement
  10576. */
  10577. XmlElement* getFirstChildElement() const noexcept { return firstChildElement; }
  10578. /** Returns the next of this element's siblings.
  10579. This can be used for iterating an element's sub-elements, e.g.
  10580. @code
  10581. XmlElement* child = myXmlDocument->getFirstChildElement();
  10582. while (child != nullptr)
  10583. {
  10584. ...do stuff with this child..
  10585. child = child->getNextElement();
  10586. }
  10587. @endcode
  10588. Note that when iterating the child elements, some of them might be
  10589. text elements as well as XML tags - use isTextElement() to work this
  10590. out.
  10591. Also, it's much easier and neater to use this method indirectly via the
  10592. forEachXmlChildElement macro.
  10593. @returns the sibling element that follows this one, or zero if this is the last
  10594. element in its parent
  10595. @see getNextElement, isTextElement, forEachXmlChildElement
  10596. */
  10597. inline XmlElement* getNextElement() const noexcept { return nextListItem; }
  10598. /** Returns the next of this element's siblings which has the specified tag
  10599. name.
  10600. This is like getNextElement(), but will scan through the list until it
  10601. finds an element with the given tag name.
  10602. @see getNextElement, forEachXmlChildElementWithTagName
  10603. */
  10604. XmlElement* getNextElementWithTagName (const String& requiredTagName) const;
  10605. /** Returns the number of sub-elements in this element.
  10606. @see getChildElement
  10607. */
  10608. int getNumChildElements() const noexcept;
  10609. /** Returns the sub-element at a certain index.
  10610. It's not very efficient to iterate the sub-elements by index - see
  10611. getNextElement() for an example of how best to iterate.
  10612. @returns the n'th child of this element, or 0 if the index is out-of-range
  10613. @see getNextElement, isTextElement, getChildByName
  10614. */
  10615. XmlElement* getChildElement (int index) const noexcept;
  10616. /** Returns the first sub-element with a given tag-name.
  10617. @param tagNameToLookFor the tag name of the element you want to find
  10618. @returns the first element with this tag name, or 0 if none is found
  10619. @see getNextElement, isTextElement, getChildElement
  10620. */
  10621. XmlElement* getChildByName (const String& tagNameToLookFor) const noexcept;
  10622. /** Appends an element to this element's list of children.
  10623. Child elements are deleted automatically when their parent is deleted, so
  10624. make sure the object that you pass in will not be deleted by anything else,
  10625. and make sure it's not already the child of another element.
  10626. @see getFirstChildElement, getNextElement, getNumChildElements,
  10627. getChildElement, removeChildElement
  10628. */
  10629. void addChildElement (XmlElement* newChildElement) noexcept;
  10630. /** Inserts an element into this element's list of children.
  10631. Child elements are deleted automatically when their parent is deleted, so
  10632. make sure the object that you pass in will not be deleted by anything else,
  10633. and make sure it's not already the child of another element.
  10634. @param newChildNode the element to add
  10635. @param indexToInsertAt the index at which to insert the new element - if this is
  10636. below zero, it will be added to the end of the list
  10637. @see addChildElement, insertChildElement
  10638. */
  10639. void insertChildElement (XmlElement* newChildNode,
  10640. int indexToInsertAt) noexcept;
  10641. /** Creates a new element with the given name and returns it, after adding it
  10642. as a child element.
  10643. This is a handy method that means that instead of writing this:
  10644. @code
  10645. XmlElement* newElement = new XmlElement ("foobar");
  10646. myParentElement->addChildElement (newElement);
  10647. @endcode
  10648. ..you could just write this:
  10649. @code
  10650. XmlElement* newElement = myParentElement->createNewChildElement ("foobar");
  10651. @endcode
  10652. */
  10653. XmlElement* createNewChildElement (const String& tagName);
  10654. /** Replaces one of this element's children with another node.
  10655. If the current element passed-in isn't actually a child of this element,
  10656. this will return false and the new one won't be added. Otherwise, the
  10657. existing element will be deleted, replaced with the new one, and it
  10658. will return true.
  10659. */
  10660. bool replaceChildElement (XmlElement* currentChildElement,
  10661. XmlElement* newChildNode) noexcept;
  10662. /** Removes a child element.
  10663. @param childToRemove the child to look for and remove
  10664. @param shouldDeleteTheChild if true, the child will be deleted, if false it'll
  10665. just remove it
  10666. */
  10667. void removeChildElement (XmlElement* childToRemove,
  10668. bool shouldDeleteTheChild) noexcept;
  10669. /** Deletes all the child elements in the element.
  10670. @see removeChildElement, deleteAllChildElementsWithTagName
  10671. */
  10672. void deleteAllChildElements() noexcept;
  10673. /** Deletes all the child elements with a given tag name.
  10674. @see removeChildElement
  10675. */
  10676. void deleteAllChildElementsWithTagName (const String& tagName) noexcept;
  10677. /** Returns true if the given element is a child of this one. */
  10678. bool containsChildElement (const XmlElement* possibleChild) const noexcept;
  10679. /** Recursively searches all sub-elements to find one that contains the specified
  10680. child element.
  10681. */
  10682. XmlElement* findParentElementOf (const XmlElement* elementToLookFor) noexcept;
  10683. /** Sorts the child elements using a comparator.
  10684. This will use a comparator object to sort the elements into order. The object
  10685. passed must have a method of the form:
  10686. @code
  10687. int compareElements (const XmlElement* first, const XmlElement* second);
  10688. @endcode
  10689. ..and this method must return:
  10690. - a value of < 0 if the first comes before the second
  10691. - a value of 0 if the two objects are equivalent
  10692. - a value of > 0 if the second comes before the first
  10693. To improve performance, the compareElements() method can be declared as static or const.
  10694. @param comparator the comparator to use for comparing elements.
  10695. @param retainOrderOfEquivalentItems if this is true, then items which the comparator
  10696. says are equivalent will be kept in the order in which they
  10697. currently appear in the array. This is slower to perform, but
  10698. may be important in some cases. If it's false, a faster algorithm
  10699. is used, but equivalent elements may be rearranged.
  10700. */
  10701. template <class ElementComparator>
  10702. void sortChildElements (ElementComparator& comparator,
  10703. bool retainOrderOfEquivalentItems = false)
  10704. {
  10705. const int num = getNumChildElements();
  10706. if (num > 1)
  10707. {
  10708. HeapBlock <XmlElement*> elems (num);
  10709. getChildElementsAsArray (elems);
  10710. sortArray (comparator, (XmlElement**) elems, 0, num - 1, retainOrderOfEquivalentItems);
  10711. reorderChildElements (elems, num);
  10712. }
  10713. }
  10714. /** Returns true if this element is a section of text.
  10715. Elements can either be an XML tag element or a secton of text, so this
  10716. is used to find out what kind of element this one is.
  10717. @see getAllText, addTextElement, deleteAllTextElements
  10718. */
  10719. bool isTextElement() const noexcept;
  10720. /** Returns the text for a text element.
  10721. Note that if you have an element like this:
  10722. @code<xyz>hello</xyz>@endcode
  10723. then calling getText on the "xyz" element won't return "hello", because that is
  10724. actually stored in a special text sub-element inside the xyz element. To get the
  10725. "hello" string, you could either call getText on the (unnamed) sub-element, or
  10726. use getAllSubText() to do this automatically.
  10727. Note that leading and trailing whitespace will be included in the string - to remove
  10728. if, just call String::trim() on the result.
  10729. @see isTextElement, getAllSubText, getChildElementAllSubText
  10730. */
  10731. const String& getText() const noexcept;
  10732. /** Sets the text in a text element.
  10733. Note that this is only a valid call if this element is a text element. If it's
  10734. not, then no action will be performed. If you're trying to add text inside a normal
  10735. element, you probably want to use addTextElement() instead.
  10736. */
  10737. void setText (const String& newText);
  10738. /** Returns all the text from this element's child nodes.
  10739. This iterates all the child elements and when it finds text elements,
  10740. it concatenates their text into a big string which it returns.
  10741. E.g. @code<xyz>hello <x>there</x> world</xyz>@endcode
  10742. if you called getAllSubText on the "xyz" element, it'd return "hello there world".
  10743. Note that leading and trailing whitespace will be included in the string - to remove
  10744. if, just call String::trim() on the result.
  10745. @see isTextElement, getChildElementAllSubText, getText, addTextElement
  10746. */
  10747. String getAllSubText() const;
  10748. /** Returns all the sub-text of a named child element.
  10749. If there is a child element with the given tag name, this will return
  10750. all of its sub-text (by calling getAllSubText() on it). If there is
  10751. no such child element, this will return the default string passed-in.
  10752. @see getAllSubText
  10753. */
  10754. String getChildElementAllSubText (const String& childTagName,
  10755. const String& defaultReturnValue) const;
  10756. /** Appends a section of text to this element.
  10757. @see isTextElement, getText, getAllSubText
  10758. */
  10759. void addTextElement (const String& text);
  10760. /** Removes all the text elements from this element.
  10761. @see isTextElement, getText, getAllSubText, addTextElement
  10762. */
  10763. void deleteAllTextElements() noexcept;
  10764. /** Creates a text element that can be added to a parent element.
  10765. */
  10766. static XmlElement* createTextElement (const String& text);
  10767. private:
  10768. struct XmlAttributeNode
  10769. {
  10770. XmlAttributeNode (const XmlAttributeNode& other) noexcept;
  10771. XmlAttributeNode (const String& name, const String& value) noexcept;
  10772. LinkedListPointer<XmlAttributeNode> nextListItem;
  10773. String name, value;
  10774. bool hasName (const String& name) const noexcept;
  10775. private:
  10776. XmlAttributeNode& operator= (const XmlAttributeNode&);
  10777. };
  10778. friend class XmlDocument;
  10779. friend class LinkedListPointer<XmlAttributeNode>;
  10780. friend class LinkedListPointer <XmlElement>;
  10781. friend class LinkedListPointer <XmlElement>::Appender;
  10782. LinkedListPointer <XmlElement> nextListItem;
  10783. LinkedListPointer <XmlElement> firstChildElement;
  10784. LinkedListPointer <XmlAttributeNode> attributes;
  10785. String tagName;
  10786. XmlElement (int) noexcept;
  10787. void copyChildrenAndAttributesFrom (const XmlElement& other);
  10788. void writeElementAsText (OutputStream& out, int indentationLevel, int lineWrapLength) const;
  10789. void getChildElementsAsArray (XmlElement**) const noexcept;
  10790. void reorderChildElements (XmlElement**, int) noexcept;
  10791. JUCE_LEAK_DETECTOR (XmlElement);
  10792. };
  10793. #endif // __JUCE_XMLELEMENT_JUCEHEADER__
  10794. /*** End of inlined file: juce_XmlElement.h ***/
  10795. /**
  10796. A set of named property values, which can be strings, integers, floating point, etc.
  10797. Effectively, this just wraps a StringPairArray in an interface that makes it easier
  10798. to load and save types other than strings.
  10799. See the PropertiesFile class for a subclass of this, which automatically broadcasts change
  10800. messages and saves/loads the list from a file.
  10801. */
  10802. class JUCE_API PropertySet
  10803. {
  10804. public:
  10805. /** Creates an empty PropertySet.
  10806. @param ignoreCaseOfKeyNames if true, the names of properties are compared in a
  10807. case-insensitive way
  10808. */
  10809. PropertySet (bool ignoreCaseOfKeyNames = false);
  10810. /** Creates a copy of another PropertySet.
  10811. */
  10812. PropertySet (const PropertySet& other);
  10813. /** Copies another PropertySet over this one.
  10814. */
  10815. PropertySet& operator= (const PropertySet& other);
  10816. /** Destructor. */
  10817. virtual ~PropertySet();
  10818. /** Returns one of the properties as a string.
  10819. If the value isn't found in this set, then this will look for it in a fallback
  10820. property set (if you've specified one with the setFallbackPropertySet() method),
  10821. and if it can't find one there, it'll return the default value passed-in.
  10822. @param keyName the name of the property to retrieve
  10823. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10824. */
  10825. String getValue (const String& keyName,
  10826. const String& defaultReturnValue = String::empty) const noexcept;
  10827. /** Returns one of the properties as an integer.
  10828. If the value isn't found in this set, then this will look for it in a fallback
  10829. property set (if you've specified one with the setFallbackPropertySet() method),
  10830. and if it can't find one there, it'll return the default value passed-in.
  10831. @param keyName the name of the property to retrieve
  10832. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10833. */
  10834. int getIntValue (const String& keyName,
  10835. const int defaultReturnValue = 0) const noexcept;
  10836. /** Returns one of the properties as an double.
  10837. If the value isn't found in this set, then this will look for it in a fallback
  10838. property set (if you've specified one with the setFallbackPropertySet() method),
  10839. and if it can't find one there, it'll return the default value passed-in.
  10840. @param keyName the name of the property to retrieve
  10841. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10842. */
  10843. double getDoubleValue (const String& keyName,
  10844. const double defaultReturnValue = 0.0) const noexcept;
  10845. /** Returns one of the properties as an boolean.
  10846. The result will be true if the string found for this key name can be parsed as a non-zero
  10847. integer.
  10848. If the value isn't found in this set, then this will look for it in a fallback
  10849. property set (if you've specified one with the setFallbackPropertySet() method),
  10850. and if it can't find one there, it'll return the default value passed-in.
  10851. @param keyName the name of the property to retrieve
  10852. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10853. */
  10854. bool getBoolValue (const String& keyName,
  10855. const bool defaultReturnValue = false) const noexcept;
  10856. /** Returns one of the properties as an XML element.
  10857. The result will a new XMLElement object that the caller must delete. If may return 0 if the
  10858. key isn't found, or if the entry contains an string that isn't valid XML.
  10859. If the value isn't found in this set, then this will look for it in a fallback
  10860. property set (if you've specified one with the setFallbackPropertySet() method),
  10861. and if it can't find one there, it'll return the default value passed-in.
  10862. @param keyName the name of the property to retrieve
  10863. */
  10864. XmlElement* getXmlValue (const String& keyName) const;
  10865. /** Sets a named property.
  10866. @param keyName the name of the property to set. (This mustn't be an empty string)
  10867. @param value the new value to set it to
  10868. */
  10869. void setValue (const String& keyName, const var& value);
  10870. /** Sets a named property to an XML element.
  10871. @param keyName the name of the property to set. (This mustn't be an empty string)
  10872. @param xml the new element to set it to. If this is zero, the value will be set to
  10873. an empty string
  10874. @see getXmlValue
  10875. */
  10876. void setValue (const String& keyName, const XmlElement* xml);
  10877. /** This copies all the values from a source PropertySet to this one.
  10878. This won't remove any existing settings, it just adds any that it finds in the source set.
  10879. */
  10880. void addAllPropertiesFrom (const PropertySet& source);
  10881. /** Deletes a property.
  10882. @param keyName the name of the property to delete. (This mustn't be an empty string)
  10883. */
  10884. void removeValue (const String& keyName);
  10885. /** Returns true if the properies include the given key. */
  10886. bool containsKey (const String& keyName) const noexcept;
  10887. /** Removes all values. */
  10888. void clear();
  10889. /** Returns the keys/value pair array containing all the properties. */
  10890. StringPairArray& getAllProperties() noexcept { return properties; }
  10891. /** Returns the lock used when reading or writing to this set */
  10892. const CriticalSection& getLock() const noexcept { return lock; }
  10893. /** Returns an XML element which encapsulates all the items in this property set.
  10894. The string parameter is the tag name that should be used for the node.
  10895. @see restoreFromXml
  10896. */
  10897. XmlElement* createXml (const String& nodeName) const;
  10898. /** Reloads a set of properties that were previously stored as XML.
  10899. The node passed in must have been created by the createXml() method.
  10900. @see createXml
  10901. */
  10902. void restoreFromXml (const XmlElement& xml);
  10903. /** Sets up a second PopertySet that will be used to look up any values that aren't
  10904. set in this one.
  10905. If you set this up to be a pointer to a second property set, then whenever one
  10906. of the getValue() methods fails to find an entry in this set, it will look up that
  10907. value in the fallback set, and if it finds it, it will return that.
  10908. Make sure that you don't delete the fallback set while it's still being used by
  10909. another set! To remove the fallback set, just call this method with a null pointer.
  10910. @see getFallbackPropertySet
  10911. */
  10912. void setFallbackPropertySet (PropertySet* fallbackProperties) noexcept;
  10913. /** Returns the fallback property set.
  10914. @see setFallbackPropertySet
  10915. */
  10916. PropertySet* getFallbackPropertySet() const noexcept { return fallbackProperties; }
  10917. protected:
  10918. /** Subclasses can override this to be told when one of the properies has been changed. */
  10919. virtual void propertyChanged();
  10920. private:
  10921. StringPairArray properties;
  10922. PropertySet* fallbackProperties;
  10923. CriticalSection lock;
  10924. bool ignoreCaseOfKeys;
  10925. JUCE_LEAK_DETECTOR (PropertySet);
  10926. };
  10927. #endif // __JUCE_PROPERTYSET_JUCEHEADER__
  10928. /*** End of inlined file: juce_PropertySet.h ***/
  10929. #endif
  10930. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  10931. /*** Start of inlined file: juce_ReferenceCountedArray.h ***/
  10932. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  10933. #define __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  10934. /**
  10935. Holds a list of objects derived from ReferenceCountedObject.
  10936. A ReferenceCountedArray holds objects derived from ReferenceCountedObject,
  10937. and takes care of incrementing and decrementing their ref counts when they
  10938. are added and removed from the array.
  10939. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  10940. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  10941. @see Array, OwnedArray, StringArray
  10942. */
  10943. template <class ObjectClass, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  10944. class ReferenceCountedArray
  10945. {
  10946. public:
  10947. typedef ReferenceCountedObjectPtr<ObjectClass> ObjectClassPtr;
  10948. /** Creates an empty array.
  10949. @see ReferenceCountedObject, Array, OwnedArray
  10950. */
  10951. ReferenceCountedArray() noexcept
  10952. : numUsed (0)
  10953. {
  10954. }
  10955. /** Creates a copy of another array */
  10956. ReferenceCountedArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) noexcept
  10957. {
  10958. const ScopedLockType lock (other.getLock());
  10959. numUsed = other.numUsed;
  10960. data.setAllocatedSize (numUsed);
  10961. memcpy (data.elements, other.data.elements, numUsed * sizeof (ObjectClass*));
  10962. for (int i = numUsed; --i >= 0;)
  10963. if (data.elements[i] != nullptr)
  10964. data.elements[i]->incReferenceCount();
  10965. }
  10966. /** Copies another array into this one.
  10967. Any existing objects in this array will first be released.
  10968. */
  10969. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& operator= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) noexcept
  10970. {
  10971. if (this != &other)
  10972. {
  10973. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse> otherCopy (other);
  10974. swapWithArray (otherCopy);
  10975. }
  10976. return *this;
  10977. }
  10978. /** Destructor.
  10979. Any objects in the array will be released, and may be deleted if not referenced from elsewhere.
  10980. */
  10981. ~ReferenceCountedArray()
  10982. {
  10983. clear();
  10984. }
  10985. /** Removes all objects from the array.
  10986. Any objects in the array that are not referenced from elsewhere will be deleted.
  10987. */
  10988. void clear()
  10989. {
  10990. const ScopedLockType lock (getLock());
  10991. while (numUsed > 0)
  10992. if (data.elements [--numUsed] != nullptr)
  10993. data.elements [numUsed]->decReferenceCount();
  10994. jassert (numUsed == 0);
  10995. data.setAllocatedSize (0);
  10996. }
  10997. /** Returns the current number of objects in the array. */
  10998. inline int size() const noexcept
  10999. {
  11000. return numUsed;
  11001. }
  11002. /** Returns a pointer to the object at this index in the array.
  11003. If the index is out-of-range, this will return a null pointer, (and
  11004. it could be null anyway, because it's ok for the array to hold null
  11005. pointers as well as objects).
  11006. @see getUnchecked
  11007. */
  11008. inline const ObjectClassPtr operator[] (const int index) const noexcept
  11009. {
  11010. const ScopedLockType lock (getLock());
  11011. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  11012. : static_cast <ObjectClass*> (nullptr);
  11013. }
  11014. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  11015. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  11016. it can be used when you're sure the index if always going to be legal.
  11017. */
  11018. inline const ObjectClassPtr getUnchecked (const int index) const noexcept
  11019. {
  11020. const ScopedLockType lock (getLock());
  11021. jassert (isPositiveAndBelow (index, numUsed));
  11022. return data.elements [index];
  11023. }
  11024. /** Returns a pointer to the first object in the array.
  11025. This will return a null pointer if the array's empty.
  11026. @see getLast
  11027. */
  11028. inline const ObjectClassPtr getFirst() const noexcept
  11029. {
  11030. const ScopedLockType lock (getLock());
  11031. return numUsed > 0 ? data.elements [0]
  11032. : static_cast <ObjectClass*> (nullptr);
  11033. }
  11034. /** Returns a pointer to the last object in the array.
  11035. This will return a null pointer if the array's empty.
  11036. @see getFirst
  11037. */
  11038. inline const ObjectClassPtr getLast() const noexcept
  11039. {
  11040. const ScopedLockType lock (getLock());
  11041. return numUsed > 0 ? data.elements [numUsed - 1]
  11042. : static_cast <ObjectClass*> (nullptr);
  11043. }
  11044. /** Returns a pointer to the first element in the array.
  11045. This method is provided for compatibility with standard C++ iteration mechanisms.
  11046. */
  11047. inline ObjectClass** begin() const noexcept
  11048. {
  11049. return data.elements;
  11050. }
  11051. /** Returns a pointer to the element which follows the last element in the array.
  11052. This method is provided for compatibility with standard C++ iteration mechanisms.
  11053. */
  11054. inline ObjectClass** end() const noexcept
  11055. {
  11056. return data.elements + numUsed;
  11057. }
  11058. /** Finds the index of the first occurrence of an object in the array.
  11059. @param objectToLookFor the object to look for
  11060. @returns the index at which the object was found, or -1 if it's not found
  11061. */
  11062. int indexOf (const ObjectClass* const objectToLookFor) const noexcept
  11063. {
  11064. const ScopedLockType lock (getLock());
  11065. ObjectClass** e = data.elements.getData();
  11066. ObjectClass** const end_ = e + numUsed;
  11067. while (e != end_)
  11068. {
  11069. if (objectToLookFor == *e)
  11070. return static_cast <int> (e - data.elements.getData());
  11071. ++e;
  11072. }
  11073. return -1;
  11074. }
  11075. /** Returns true if the array contains a specified object.
  11076. @param objectToLookFor the object to look for
  11077. @returns true if the object is in the array
  11078. */
  11079. bool contains (const ObjectClass* const objectToLookFor) const noexcept
  11080. {
  11081. const ScopedLockType lock (getLock());
  11082. ObjectClass** e = data.elements.getData();
  11083. ObjectClass** const end_ = e + numUsed;
  11084. while (e != end_)
  11085. {
  11086. if (objectToLookFor == *e)
  11087. return true;
  11088. ++e;
  11089. }
  11090. return false;
  11091. }
  11092. /** Appends a new object to the end of the array.
  11093. This will increase the new object's reference count.
  11094. @param newObject the new object to add to the array
  11095. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  11096. */
  11097. void add (ObjectClass* const newObject) noexcept
  11098. {
  11099. const ScopedLockType lock (getLock());
  11100. data.ensureAllocatedSize (numUsed + 1);
  11101. data.elements [numUsed++] = newObject;
  11102. if (newObject != nullptr)
  11103. newObject->incReferenceCount();
  11104. }
  11105. /** Inserts a new object into the array at the given index.
  11106. If the index is less than 0 or greater than the size of the array, the
  11107. element will be added to the end of the array.
  11108. Otherwise, it will be inserted into the array, moving all the later elements
  11109. along to make room.
  11110. This will increase the new object's reference count.
  11111. @param indexToInsertAt the index at which the new element should be inserted
  11112. @param newObject the new object to add to the array
  11113. @see add, addSorted, addIfNotAlreadyThere, set
  11114. */
  11115. void insert (int indexToInsertAt,
  11116. ObjectClass* const newObject) noexcept
  11117. {
  11118. if (indexToInsertAt >= 0)
  11119. {
  11120. const ScopedLockType lock (getLock());
  11121. if (indexToInsertAt > numUsed)
  11122. indexToInsertAt = numUsed;
  11123. data.ensureAllocatedSize (numUsed + 1);
  11124. ObjectClass** const e = data.elements + indexToInsertAt;
  11125. const int numToMove = numUsed - indexToInsertAt;
  11126. if (numToMove > 0)
  11127. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  11128. *e = newObject;
  11129. if (newObject != nullptr)
  11130. newObject->incReferenceCount();
  11131. ++numUsed;
  11132. }
  11133. else
  11134. {
  11135. add (newObject);
  11136. }
  11137. }
  11138. /** Appends a new object at the end of the array as long as the array doesn't
  11139. already contain it.
  11140. If the array already contains a matching object, nothing will be done.
  11141. @param newObject the new object to add to the array
  11142. */
  11143. void addIfNotAlreadyThere (ObjectClass* const newObject) noexcept
  11144. {
  11145. const ScopedLockType lock (getLock());
  11146. if (! contains (newObject))
  11147. add (newObject);
  11148. }
  11149. /** Replaces an object in the array with a different one.
  11150. If the index is less than zero, this method does nothing.
  11151. If the index is beyond the end of the array, the new object is added to the end of the array.
  11152. The object being added has its reference count increased, and if it's replacing
  11153. another object, then that one has its reference count decreased, and may be deleted.
  11154. @param indexToChange the index whose value you want to change
  11155. @param newObject the new value to set for this index.
  11156. @see add, insert, remove
  11157. */
  11158. void set (const int indexToChange,
  11159. ObjectClass* const newObject)
  11160. {
  11161. if (indexToChange >= 0)
  11162. {
  11163. const ScopedLockType lock (getLock());
  11164. if (newObject != nullptr)
  11165. newObject->incReferenceCount();
  11166. if (indexToChange < numUsed)
  11167. {
  11168. if (data.elements [indexToChange] != nullptr)
  11169. data.elements [indexToChange]->decReferenceCount();
  11170. data.elements [indexToChange] = newObject;
  11171. }
  11172. else
  11173. {
  11174. data.ensureAllocatedSize (numUsed + 1);
  11175. data.elements [numUsed++] = newObject;
  11176. }
  11177. }
  11178. }
  11179. /** Adds elements from another array to the end of this array.
  11180. @param arrayToAddFrom the array from which to copy the elements
  11181. @param startIndex the first element of the other array to start copying from
  11182. @param numElementsToAdd how many elements to add from the other array. If this
  11183. value is negative or greater than the number of available elements,
  11184. all available elements will be copied.
  11185. @see add
  11186. */
  11187. void addArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& arrayToAddFrom,
  11188. int startIndex = 0,
  11189. int numElementsToAdd = -1) noexcept
  11190. {
  11191. const ScopedLockType lock1 (arrayToAddFrom.getLock());
  11192. {
  11193. const ScopedLockType lock2 (getLock());
  11194. if (startIndex < 0)
  11195. {
  11196. jassertfalse;
  11197. startIndex = 0;
  11198. }
  11199. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  11200. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  11201. if (numElementsToAdd > 0)
  11202. {
  11203. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  11204. while (--numElementsToAdd >= 0)
  11205. add (arrayToAddFrom.getUnchecked (startIndex++));
  11206. }
  11207. }
  11208. }
  11209. /** Inserts a new object into the array assuming that the array is sorted.
  11210. This will use a comparator to find the position at which the new object
  11211. should go. If the array isn't sorted, the behaviour of this
  11212. method will be unpredictable.
  11213. @param comparator the comparator object to use to compare the elements - see the
  11214. sort() method for details about this object's form
  11215. @param newObject the new object to insert to the array
  11216. @returns the index at which the new object was added
  11217. @see add, sort
  11218. */
  11219. template <class ElementComparator>
  11220. int addSorted (ElementComparator& comparator, ObjectClass* newObject) noexcept
  11221. {
  11222. const ScopedLockType lock (getLock());
  11223. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  11224. insert (index, newObject);
  11225. return index;
  11226. }
  11227. /** Inserts or replaces an object in the array, assuming it is sorted.
  11228. This is similar to addSorted, but if a matching element already exists, then it will be
  11229. replaced by the new one, rather than the new one being added as well.
  11230. */
  11231. template <class ElementComparator>
  11232. void addOrReplaceSorted (ElementComparator& comparator,
  11233. ObjectClass* newObject) noexcept
  11234. {
  11235. const ScopedLockType lock (getLock());
  11236. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  11237. if (index > 0 && comparator.compareElements (newObject, data.elements [index - 1]) == 0)
  11238. set (index - 1, newObject); // replace an existing object that matches
  11239. else
  11240. insert (index, newObject); // no match, so insert the new one
  11241. }
  11242. /** Removes an object from the array.
  11243. This will remove the object at a given index and move back all the
  11244. subsequent objects to close the gap.
  11245. If the index passed in is out-of-range, nothing will happen.
  11246. The object that is removed will have its reference count decreased,
  11247. and may be deleted if not referenced from elsewhere.
  11248. @param indexToRemove the index of the element to remove
  11249. @see removeObject, removeRange
  11250. */
  11251. void remove (const int indexToRemove)
  11252. {
  11253. const ScopedLockType lock (getLock());
  11254. if (isPositiveAndBelow (indexToRemove, numUsed))
  11255. {
  11256. ObjectClass** const e = data.elements + indexToRemove;
  11257. if (*e != nullptr)
  11258. (*e)->decReferenceCount();
  11259. --numUsed;
  11260. const int numberToShift = numUsed - indexToRemove;
  11261. if (numberToShift > 0)
  11262. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  11263. if ((numUsed << 1) < data.numAllocated)
  11264. minimiseStorageOverheads();
  11265. }
  11266. }
  11267. /** Removes and returns an object from the array.
  11268. This will remove the object at a given index and return it, moving back all
  11269. the subsequent objects to close the gap. If the index passed in is out-of-range,
  11270. nothing will happen and a null pointer will be returned.
  11271. @param indexToRemove the index of the element to remove
  11272. @see remove, removeObject, removeRange
  11273. */
  11274. const ObjectClassPtr removeAndReturn (const int indexToRemove)
  11275. {
  11276. ObjectClassPtr removedItem;
  11277. const ScopedLockType lock (getLock());
  11278. if (isPositiveAndBelow (indexToRemove, numUsed))
  11279. {
  11280. ObjectClass** const e = data.elements + indexToRemove;
  11281. if (*e != nullptr)
  11282. {
  11283. removedItem = *e;
  11284. (*e)->decReferenceCount();
  11285. }
  11286. --numUsed;
  11287. const int numberToShift = numUsed - indexToRemove;
  11288. if (numberToShift > 0)
  11289. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  11290. if ((numUsed << 1) < data.numAllocated)
  11291. minimiseStorageOverheads();
  11292. }
  11293. return removedItem;
  11294. }
  11295. /** Removes the first occurrence of a specified object from the array.
  11296. If the item isn't found, no action is taken. If it is found, it is
  11297. removed and has its reference count decreased.
  11298. @param objectToRemove the object to try to remove
  11299. @see remove, removeRange
  11300. */
  11301. void removeObject (ObjectClass* const objectToRemove)
  11302. {
  11303. const ScopedLockType lock (getLock());
  11304. remove (indexOf (objectToRemove));
  11305. }
  11306. /** Removes a range of objects from the array.
  11307. This will remove a set of objects, starting from the given index,
  11308. and move any subsequent elements down to close the gap.
  11309. If the range extends beyond the bounds of the array, it will
  11310. be safely clipped to the size of the array.
  11311. The objects that are removed will have their reference counts decreased,
  11312. and may be deleted if not referenced from elsewhere.
  11313. @param startIndex the index of the first object to remove
  11314. @param numberToRemove how many objects should be removed
  11315. @see remove, removeObject
  11316. */
  11317. void removeRange (const int startIndex,
  11318. const int numberToRemove)
  11319. {
  11320. const ScopedLockType lock (getLock());
  11321. const int start = jlimit (0, numUsed, startIndex);
  11322. const int end_ = jlimit (0, numUsed, startIndex + numberToRemove);
  11323. if (end_ > start)
  11324. {
  11325. int i;
  11326. for (i = start; i < end_; ++i)
  11327. {
  11328. if (data.elements[i] != nullptr)
  11329. {
  11330. data.elements[i]->decReferenceCount();
  11331. data.elements[i] = nullptr; // (in case one of the destructors accesses this array and hits a dangling pointer)
  11332. }
  11333. }
  11334. const int rangeSize = end_ - start;
  11335. ObjectClass** e = data.elements + start;
  11336. i = numUsed - end_;
  11337. numUsed -= rangeSize;
  11338. while (--i >= 0)
  11339. {
  11340. *e = e [rangeSize];
  11341. ++e;
  11342. }
  11343. if ((numUsed << 1) < data.numAllocated)
  11344. minimiseStorageOverheads();
  11345. }
  11346. }
  11347. /** Removes the last n objects from the array.
  11348. The objects that are removed will have their reference counts decreased,
  11349. and may be deleted if not referenced from elsewhere.
  11350. @param howManyToRemove how many objects to remove from the end of the array
  11351. @see remove, removeObject, removeRange
  11352. */
  11353. void removeLast (int howManyToRemove = 1)
  11354. {
  11355. const ScopedLockType lock (getLock());
  11356. if (howManyToRemove > numUsed)
  11357. howManyToRemove = numUsed;
  11358. while (--howManyToRemove >= 0)
  11359. remove (numUsed - 1);
  11360. }
  11361. /** Swaps a pair of objects in the array.
  11362. If either of the indexes passed in is out-of-range, nothing will happen,
  11363. otherwise the two objects at these positions will be exchanged.
  11364. */
  11365. void swap (const int index1,
  11366. const int index2) noexcept
  11367. {
  11368. const ScopedLockType lock (getLock());
  11369. if (isPositiveAndBelow (index1, numUsed)
  11370. && isPositiveAndBelow (index2, numUsed))
  11371. {
  11372. std::swap (data.elements [index1],
  11373. data.elements [index2]);
  11374. }
  11375. }
  11376. /** Moves one of the objects to a different position.
  11377. This will move the object to a specified index, shuffling along
  11378. any intervening elements as required.
  11379. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  11380. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  11381. @param currentIndex the index of the object to be moved. If this isn't a
  11382. valid index, then nothing will be done
  11383. @param newIndex the index at which you'd like this object to end up. If this
  11384. is less than zero, it will be moved to the end of the array
  11385. */
  11386. void move (const int currentIndex,
  11387. int newIndex) noexcept
  11388. {
  11389. if (currentIndex != newIndex)
  11390. {
  11391. const ScopedLockType lock (getLock());
  11392. if (isPositiveAndBelow (currentIndex, numUsed))
  11393. {
  11394. if (! isPositiveAndBelow (newIndex, numUsed))
  11395. newIndex = numUsed - 1;
  11396. ObjectClass* const value = data.elements [currentIndex];
  11397. if (newIndex > currentIndex)
  11398. {
  11399. memmove (data.elements + currentIndex,
  11400. data.elements + currentIndex + 1,
  11401. (newIndex - currentIndex) * sizeof (ObjectClass*));
  11402. }
  11403. else
  11404. {
  11405. memmove (data.elements + newIndex + 1,
  11406. data.elements + newIndex,
  11407. (currentIndex - newIndex) * sizeof (ObjectClass*));
  11408. }
  11409. data.elements [newIndex] = value;
  11410. }
  11411. }
  11412. }
  11413. /** This swaps the contents of this array with those of another array.
  11414. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  11415. because it just swaps their internal pointers.
  11416. */
  11417. void swapWithArray (ReferenceCountedArray& otherArray) noexcept
  11418. {
  11419. const ScopedLockType lock1 (getLock());
  11420. const ScopedLockType lock2 (otherArray.getLock());
  11421. data.swapWith (otherArray.data);
  11422. std::swap (numUsed, otherArray.numUsed);
  11423. }
  11424. /** Compares this array to another one.
  11425. @returns true only if the other array contains the same objects in the same order
  11426. */
  11427. bool operator== (const ReferenceCountedArray& other) const noexcept
  11428. {
  11429. const ScopedLockType lock2 (other.getLock());
  11430. const ScopedLockType lock1 (getLock());
  11431. if (numUsed != other.numUsed)
  11432. return false;
  11433. for (int i = numUsed; --i >= 0;)
  11434. if (data.elements [i] != other.data.elements [i])
  11435. return false;
  11436. return true;
  11437. }
  11438. /** Compares this array to another one.
  11439. @see operator==
  11440. */
  11441. bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const noexcept
  11442. {
  11443. return ! operator== (other);
  11444. }
  11445. /** Sorts the elements in the array.
  11446. This will use a comparator object to sort the elements into order. The object
  11447. passed must have a method of the form:
  11448. @code
  11449. int compareElements (ElementType first, ElementType second);
  11450. @endcode
  11451. ..and this method must return:
  11452. - a value of < 0 if the first comes before the second
  11453. - a value of 0 if the two objects are equivalent
  11454. - a value of > 0 if the second comes before the first
  11455. To improve performance, the compareElements() method can be declared as static or const.
  11456. @param comparator the comparator to use for comparing elements.
  11457. @param retainOrderOfEquivalentItems if this is true, then items
  11458. which the comparator says are equivalent will be
  11459. kept in the order in which they currently appear
  11460. in the array. This is slower to perform, but may
  11461. be important in some cases. If it's false, a faster
  11462. algorithm is used, but equivalent elements may be
  11463. rearranged.
  11464. @see sortArray
  11465. */
  11466. template <class ElementComparator>
  11467. void sort (ElementComparator& comparator,
  11468. const bool retainOrderOfEquivalentItems = false) const noexcept
  11469. {
  11470. (void) comparator; // if you pass in an object with a static compareElements() method, this
  11471. // avoids getting warning messages about the parameter being unused
  11472. const ScopedLockType lock (getLock());
  11473. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  11474. }
  11475. /** Reduces the amount of storage being used by the array.
  11476. Arrays typically allocate slightly more storage than they need, and after
  11477. removing elements, they may have quite a lot of unused space allocated.
  11478. This method will reduce the amount of allocated storage to a minimum.
  11479. */
  11480. void minimiseStorageOverheads() noexcept
  11481. {
  11482. const ScopedLockType lock (getLock());
  11483. data.shrinkToNoMoreThan (numUsed);
  11484. }
  11485. /** Returns the CriticalSection that locks this array.
  11486. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  11487. an object of ScopedLockType as an RAII lock for it.
  11488. */
  11489. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return data; }
  11490. /** Returns the type of scoped lock to use for locking this array */
  11491. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  11492. private:
  11493. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  11494. int numUsed;
  11495. };
  11496. #endif // __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  11497. /*** End of inlined file: juce_ReferenceCountedArray.h ***/
  11498. #endif
  11499. #ifndef __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  11500. /*** Start of inlined file: juce_ScopedValueSetter.h ***/
  11501. #ifndef __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  11502. #define __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  11503. /**
  11504. Helper class providing an RAII-based mechanism for temporarily setting and
  11505. then re-setting a value.
  11506. E.g. @code
  11507. int x = 1;
  11508. {
  11509. ScopedValueSetter setter (x, 2);
  11510. // x is now 2
  11511. }
  11512. // x is now 1 again
  11513. {
  11514. ScopedValueSetter setter (x, 3, 4);
  11515. // x is now 3
  11516. }
  11517. // x is now 4
  11518. @endcode
  11519. */
  11520. template <typename ValueType>
  11521. class ScopedValueSetter
  11522. {
  11523. public:
  11524. /** Creates a ScopedValueSetter that will immediately change the specified value to the
  11525. given new value, and will then reset it to its original value when this object is deleted.
  11526. */
  11527. ScopedValueSetter (ValueType& valueToSet,
  11528. const ValueType& newValue)
  11529. : value (valueToSet),
  11530. originalValue (valueToSet)
  11531. {
  11532. valueToSet = newValue;
  11533. }
  11534. /** Creates a ScopedValueSetter that will immediately change the specified value to the
  11535. given new value, and will then reset it to be valueWhenDeleted when this object is deleted.
  11536. */
  11537. ScopedValueSetter (ValueType& valueToSet,
  11538. const ValueType& newValue,
  11539. const ValueType& valueWhenDeleted)
  11540. : value (valueToSet),
  11541. originalValue (valueWhenDeleted)
  11542. {
  11543. valueToSet = newValue;
  11544. }
  11545. ~ScopedValueSetter()
  11546. {
  11547. value = originalValue;
  11548. }
  11549. private:
  11550. ValueType& value;
  11551. const ValueType originalValue;
  11552. JUCE_DECLARE_NON_COPYABLE (ScopedValueSetter);
  11553. };
  11554. #endif // __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  11555. /*** End of inlined file: juce_ScopedValueSetter.h ***/
  11556. #endif
  11557. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  11558. /*** Start of inlined file: juce_SortedSet.h ***/
  11559. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  11560. #define __JUCE_SORTEDSET_JUCEHEADER__
  11561. #if JUCE_MSVC
  11562. #pragma warning (push)
  11563. #pragma warning (disable: 4512)
  11564. #endif
  11565. /**
  11566. Holds a set of unique primitive objects, such as ints or doubles.
  11567. A set can only hold one item with a given value, so if for example it's a
  11568. set of integers, attempting to add the same integer twice will do nothing
  11569. the second time.
  11570. Internally, the list of items is kept sorted (which means that whatever
  11571. kind of primitive type is used must support the ==, <, >, <= and >= operators
  11572. to determine the order), and searching the set for known values is very fast
  11573. because it uses a binary-chop method.
  11574. Note that if you're using a class or struct as the element type, it must be
  11575. capable of being copied or moved with a straightforward memcpy, rather than
  11576. needing construction and destruction code.
  11577. To make all the set's methods thread-safe, pass in "CriticalSection" as the templated
  11578. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  11579. @see Array, OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  11580. */
  11581. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  11582. class SortedSet
  11583. {
  11584. public:
  11585. /** Creates an empty set. */
  11586. SortedSet() noexcept
  11587. : numUsed (0)
  11588. {
  11589. }
  11590. /** Creates a copy of another set.
  11591. @param other the set to copy
  11592. */
  11593. SortedSet (const SortedSet& other) noexcept
  11594. {
  11595. const ScopedLockType lock (other.getLock());
  11596. numUsed = other.numUsed;
  11597. data.setAllocatedSize (other.numUsed);
  11598. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  11599. }
  11600. /** Destructor. */
  11601. ~SortedSet() noexcept
  11602. {
  11603. }
  11604. /** Copies another set over this one.
  11605. @param other the set to copy
  11606. */
  11607. SortedSet& operator= (const SortedSet& other) noexcept
  11608. {
  11609. if (this != &other)
  11610. {
  11611. const ScopedLockType lock1 (other.getLock());
  11612. const ScopedLockType lock2 (getLock());
  11613. data.ensureAllocatedSize (other.size());
  11614. numUsed = other.numUsed;
  11615. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  11616. minimiseStorageOverheads();
  11617. }
  11618. return *this;
  11619. }
  11620. /** Compares this set to another one.
  11621. Two sets are considered equal if they both contain the same set of
  11622. elements.
  11623. @param other the other set to compare with
  11624. */
  11625. bool operator== (const SortedSet<ElementType>& other) const noexcept
  11626. {
  11627. const ScopedLockType lock (getLock());
  11628. if (numUsed != other.numUsed)
  11629. return false;
  11630. for (int i = numUsed; --i >= 0;)
  11631. if (! (data.elements[i] == other.data.elements[i]))
  11632. return false;
  11633. return true;
  11634. }
  11635. /** Compares this set to another one.
  11636. Two sets are considered equal if they both contain the same set of
  11637. elements.
  11638. @param other the other set to compare with
  11639. */
  11640. bool operator!= (const SortedSet<ElementType>& other) const noexcept
  11641. {
  11642. return ! operator== (other);
  11643. }
  11644. /** Removes all elements from the set.
  11645. This will remove all the elements, and free any storage that the set is
  11646. using. To clear it without freeing the storage, use the clearQuick()
  11647. method instead.
  11648. @see clearQuick
  11649. */
  11650. void clear() noexcept
  11651. {
  11652. const ScopedLockType lock (getLock());
  11653. data.setAllocatedSize (0);
  11654. numUsed = 0;
  11655. }
  11656. /** Removes all elements from the set without freeing the array's allocated storage.
  11657. @see clear
  11658. */
  11659. void clearQuick() noexcept
  11660. {
  11661. const ScopedLockType lock (getLock());
  11662. numUsed = 0;
  11663. }
  11664. /** Returns the current number of elements in the set.
  11665. */
  11666. inline int size() const noexcept
  11667. {
  11668. return numUsed;
  11669. }
  11670. /** Returns one of the elements in the set.
  11671. If the index passed in is beyond the range of valid elements, this
  11672. will return zero.
  11673. If you're certain that the index will always be a valid element, you
  11674. can call getUnchecked() instead, which is faster.
  11675. @param index the index of the element being requested (0 is the first element in the set)
  11676. @see getUnchecked, getFirst, getLast
  11677. */
  11678. inline ElementType operator[] (const int index) const noexcept
  11679. {
  11680. const ScopedLockType lock (getLock());
  11681. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  11682. : ElementType();
  11683. }
  11684. /** Returns one of the elements in the set, without checking the index passed in.
  11685. Unlike the operator[] method, this will try to return an element without
  11686. checking that the index is within the bounds of the set, so should only
  11687. be used when you're confident that it will always be a valid index.
  11688. @param index the index of the element being requested (0 is the first element in the set)
  11689. @see operator[], getFirst, getLast
  11690. */
  11691. inline ElementType getUnchecked (const int index) const noexcept
  11692. {
  11693. const ScopedLockType lock (getLock());
  11694. jassert (isPositiveAndBelow (index, numUsed));
  11695. return data.elements [index];
  11696. }
  11697. /** Returns a direct reference to one of the elements in the set, without checking the index passed in.
  11698. This is like getUnchecked, but returns a direct reference to the element, so that
  11699. you can alter it directly. Obviously this can be dangerous, so only use it when
  11700. absolutely necessary.
  11701. @param index the index of the element being requested (0 is the first element in the array)
  11702. */
  11703. inline ElementType& getReference (const int index) const noexcept
  11704. {
  11705. const ScopedLockType lock (getLock());
  11706. jassert (isPositiveAndBelow (index, numUsed));
  11707. return data.elements [index];
  11708. }
  11709. /** Returns the first element in the set, or 0 if the set is empty.
  11710. @see operator[], getUnchecked, getLast
  11711. */
  11712. inline ElementType getFirst() const noexcept
  11713. {
  11714. const ScopedLockType lock (getLock());
  11715. return numUsed > 0 ? data.elements [0] : ElementType();
  11716. }
  11717. /** Returns the last element in the set, or 0 if the set is empty.
  11718. @see operator[], getUnchecked, getFirst
  11719. */
  11720. inline ElementType getLast() const noexcept
  11721. {
  11722. const ScopedLockType lock (getLock());
  11723. return numUsed > 0 ? data.elements [numUsed - 1] : ElementType();
  11724. }
  11725. /** Returns a pointer to the first element in the set.
  11726. This method is provided for compatibility with standard C++ iteration mechanisms.
  11727. */
  11728. inline ElementType* begin() const noexcept
  11729. {
  11730. return data.elements;
  11731. }
  11732. /** Returns a pointer to the element which follows the last element in the set.
  11733. This method is provided for compatibility with standard C++ iteration mechanisms.
  11734. */
  11735. inline ElementType* end() const noexcept
  11736. {
  11737. return data.elements + numUsed;
  11738. }
  11739. /** Finds the index of the first element which matches the value passed in.
  11740. This will search the set for the given object, and return the index
  11741. of its first occurrence. If the object isn't found, the method will return -1.
  11742. @param elementToLookFor the value or object to look for
  11743. @returns the index of the object, or -1 if it's not found
  11744. */
  11745. int indexOf (const ElementType elementToLookFor) const noexcept
  11746. {
  11747. const ScopedLockType lock (getLock());
  11748. int start = 0;
  11749. int end_ = numUsed;
  11750. for (;;)
  11751. {
  11752. if (start >= end_)
  11753. {
  11754. return -1;
  11755. }
  11756. else if (elementToLookFor == data.elements [start])
  11757. {
  11758. return start;
  11759. }
  11760. else
  11761. {
  11762. const int halfway = (start + end_) >> 1;
  11763. if (halfway == start)
  11764. return -1;
  11765. else if (elementToLookFor < data.elements [halfway])
  11766. end_ = halfway;
  11767. else
  11768. start = halfway;
  11769. }
  11770. }
  11771. }
  11772. /** Returns true if the set contains at least one occurrence of an object.
  11773. @param elementToLookFor the value or object to look for
  11774. @returns true if the item is found
  11775. */
  11776. bool contains (const ElementType elementToLookFor) const noexcept
  11777. {
  11778. const ScopedLockType lock (getLock());
  11779. int start = 0;
  11780. int end_ = numUsed;
  11781. for (;;)
  11782. {
  11783. if (start >= end_)
  11784. {
  11785. return false;
  11786. }
  11787. else if (elementToLookFor == data.elements [start])
  11788. {
  11789. return true;
  11790. }
  11791. else
  11792. {
  11793. const int halfway = (start + end_) >> 1;
  11794. if (halfway == start)
  11795. return false;
  11796. else if (elementToLookFor < data.elements [halfway])
  11797. end_ = halfway;
  11798. else
  11799. start = halfway;
  11800. }
  11801. }
  11802. }
  11803. /** Adds a new element to the set, (as long as it's not already in there).
  11804. @param newElement the new object to add to the set
  11805. @see set, insert, addIfNotAlreadyThere, addSorted, addSet, addArray
  11806. */
  11807. void add (const ElementType newElement) noexcept
  11808. {
  11809. const ScopedLockType lock (getLock());
  11810. int start = 0;
  11811. int end_ = numUsed;
  11812. for (;;)
  11813. {
  11814. if (start >= end_)
  11815. {
  11816. jassert (start <= end_);
  11817. insertInternal (start, newElement);
  11818. break;
  11819. }
  11820. else if (newElement == data.elements [start])
  11821. {
  11822. break;
  11823. }
  11824. else
  11825. {
  11826. const int halfway = (start + end_) >> 1;
  11827. if (halfway == start)
  11828. {
  11829. if (newElement < data.elements [halfway])
  11830. insertInternal (start, newElement);
  11831. else
  11832. insertInternal (start + 1, newElement);
  11833. break;
  11834. }
  11835. else if (newElement < data.elements [halfway])
  11836. end_ = halfway;
  11837. else
  11838. start = halfway;
  11839. }
  11840. }
  11841. }
  11842. /** Adds elements from an array to this set.
  11843. @param elementsToAdd the array of elements to add
  11844. @param numElementsToAdd how many elements are in this other array
  11845. @see add
  11846. */
  11847. void addArray (const ElementType* elementsToAdd,
  11848. int numElementsToAdd) noexcept
  11849. {
  11850. const ScopedLockType lock (getLock());
  11851. while (--numElementsToAdd >= 0)
  11852. add (*elementsToAdd++);
  11853. }
  11854. /** Adds elements from another set to this one.
  11855. @param setToAddFrom the set from which to copy the elements
  11856. @param startIndex the first element of the other set to start copying from
  11857. @param numElementsToAdd how many elements to add from the other set. If this
  11858. value is negative or greater than the number of available elements,
  11859. all available elements will be copied.
  11860. @see add
  11861. */
  11862. template <class OtherSetType>
  11863. void addSet (const OtherSetType& setToAddFrom,
  11864. int startIndex = 0,
  11865. int numElementsToAdd = -1) noexcept
  11866. {
  11867. const typename OtherSetType::ScopedLockType lock1 (setToAddFrom.getLock());
  11868. {
  11869. const ScopedLockType lock2 (getLock());
  11870. jassert (this != &setToAddFrom);
  11871. if (this != &setToAddFrom)
  11872. {
  11873. if (startIndex < 0)
  11874. {
  11875. jassertfalse;
  11876. startIndex = 0;
  11877. }
  11878. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > setToAddFrom.size())
  11879. numElementsToAdd = setToAddFrom.size() - startIndex;
  11880. addArray (setToAddFrom.elements + startIndex, numElementsToAdd);
  11881. }
  11882. }
  11883. }
  11884. /** Removes an element from the set.
  11885. This will remove the element at a given index.
  11886. If the index passed in is out-of-range, nothing will happen.
  11887. @param indexToRemove the index of the element to remove
  11888. @returns the element that has been removed
  11889. @see removeValue, removeRange
  11890. */
  11891. ElementType remove (const int indexToRemove) noexcept
  11892. {
  11893. const ScopedLockType lock (getLock());
  11894. if (isPositiveAndBelow (indexToRemove, numUsed))
  11895. {
  11896. --numUsed;
  11897. ElementType* const e = data.elements + indexToRemove;
  11898. ElementType const removed = *e;
  11899. const int numberToShift = numUsed - indexToRemove;
  11900. if (numberToShift > 0)
  11901. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  11902. if ((numUsed << 1) < data.numAllocated)
  11903. minimiseStorageOverheads();
  11904. return removed;
  11905. }
  11906. return ElementType();
  11907. }
  11908. /** Removes an item from the set.
  11909. This will remove the given element from the set, if it's there.
  11910. @param valueToRemove the object to try to remove
  11911. @see remove, removeRange
  11912. */
  11913. void removeValue (const ElementType valueToRemove) noexcept
  11914. {
  11915. const ScopedLockType lock (getLock());
  11916. remove (indexOf (valueToRemove));
  11917. }
  11918. /** Removes any elements which are also in another set.
  11919. @param otherSet the other set in which to look for elements to remove
  11920. @see removeValuesNotIn, remove, removeValue, removeRange
  11921. */
  11922. template <class OtherSetType>
  11923. void removeValuesIn (const OtherSetType& otherSet) noexcept
  11924. {
  11925. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  11926. const ScopedLockType lock2 (getLock());
  11927. if (this == &otherSet)
  11928. {
  11929. clear();
  11930. }
  11931. else
  11932. {
  11933. if (otherSet.size() > 0)
  11934. {
  11935. for (int i = numUsed; --i >= 0;)
  11936. if (otherSet.contains (data.elements [i]))
  11937. remove (i);
  11938. }
  11939. }
  11940. }
  11941. /** Removes any elements which are not found in another set.
  11942. Only elements which occur in this other set will be retained.
  11943. @param otherSet the set in which to look for elements NOT to remove
  11944. @see removeValuesIn, remove, removeValue, removeRange
  11945. */
  11946. template <class OtherSetType>
  11947. void removeValuesNotIn (const OtherSetType& otherSet) noexcept
  11948. {
  11949. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  11950. const ScopedLockType lock2 (getLock());
  11951. if (this != &otherSet)
  11952. {
  11953. if (otherSet.size() <= 0)
  11954. {
  11955. clear();
  11956. }
  11957. else
  11958. {
  11959. for (int i = numUsed; --i >= 0;)
  11960. if (! otherSet.contains (data.elements [i]))
  11961. remove (i);
  11962. }
  11963. }
  11964. }
  11965. /** Reduces the amount of storage being used by the set.
  11966. Sets typically allocate slightly more storage than they need, and after
  11967. removing elements, they may have quite a lot of unused space allocated.
  11968. This method will reduce the amount of allocated storage to a minimum.
  11969. */
  11970. void minimiseStorageOverheads() noexcept
  11971. {
  11972. const ScopedLockType lock (getLock());
  11973. data.shrinkToNoMoreThan (numUsed);
  11974. }
  11975. /** Increases the set's internal storage to hold a minimum number of elements.
  11976. Calling this before adding a large known number of elements means that
  11977. the set won't have to keep dynamically resizing itself as the elements
  11978. are added, and it'll therefore be more efficient.
  11979. */
  11980. void ensureStorageAllocated (const int minNumElements)
  11981. {
  11982. const ScopedLockType lock (getLock());
  11983. data.ensureAllocatedSize (minNumElements);
  11984. }
  11985. /** Returns the CriticalSection that locks this array.
  11986. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  11987. an object of ScopedLockType as an RAII lock for it.
  11988. */
  11989. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return data; }
  11990. /** Returns the type of scoped lock to use for locking this array */
  11991. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  11992. private:
  11993. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  11994. int numUsed;
  11995. void insertInternal (const int indexToInsertAt, const ElementType newElement) noexcept
  11996. {
  11997. data.ensureAllocatedSize (numUsed + 1);
  11998. ElementType* const insertPos = data.elements + indexToInsertAt;
  11999. const int numberToMove = numUsed - indexToInsertAt;
  12000. if (numberToMove > 0)
  12001. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  12002. *insertPos = newElement;
  12003. ++numUsed;
  12004. }
  12005. };
  12006. #if JUCE_MSVC
  12007. #pragma warning (pop)
  12008. #endif
  12009. #endif // __JUCE_SORTEDSET_JUCEHEADER__
  12010. /*** End of inlined file: juce_SortedSet.h ***/
  12011. #endif
  12012. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  12013. /*** Start of inlined file: juce_SparseSet.h ***/
  12014. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  12015. #define __JUCE_SPARSESET_JUCEHEADER__
  12016. /*** Start of inlined file: juce_Range.h ***/
  12017. #ifndef __JUCE_RANGE_JUCEHEADER__
  12018. #define __JUCE_RANGE_JUCEHEADER__
  12019. /** A general-purpose range object, that simply represents any linear range with
  12020. a start and end point.
  12021. The templated parameter is expected to be a primitive integer or floating point
  12022. type, though class types could also be used if they behave in a number-like way.
  12023. */
  12024. template <typename ValueType>
  12025. class Range
  12026. {
  12027. public:
  12028. /** Constructs an empty range. */
  12029. Range() noexcept
  12030. : start (ValueType()), end (ValueType())
  12031. {
  12032. }
  12033. /** Constructs a range with given start and end values. */
  12034. Range (const ValueType start_, const ValueType end_) noexcept
  12035. : start (start_), end (jmax (start_, end_))
  12036. {
  12037. }
  12038. /** Constructs a copy of another range. */
  12039. Range (const Range& other) noexcept
  12040. : start (other.start), end (other.end)
  12041. {
  12042. }
  12043. /** Copies another range object. */
  12044. Range& operator= (const Range& other) noexcept
  12045. {
  12046. start = other.start;
  12047. end = other.end;
  12048. return *this;
  12049. }
  12050. /** Destructor. */
  12051. ~Range() noexcept
  12052. {
  12053. }
  12054. /** Returns the range that lies between two positions (in either order). */
  12055. static Range between (const ValueType position1, const ValueType position2) noexcept
  12056. {
  12057. return (position1 < position2) ? Range (position1, position2)
  12058. : Range (position2, position1);
  12059. }
  12060. /** Returns a range with the specified start position and a length of zero. */
  12061. static Range emptyRange (const ValueType start) noexcept
  12062. {
  12063. return Range (start, start);
  12064. }
  12065. /** Returns the start of the range. */
  12066. inline ValueType getStart() const noexcept { return start; }
  12067. /** Returns the length of the range. */
  12068. inline ValueType getLength() const noexcept { return end - start; }
  12069. /** Returns the end of the range. */
  12070. inline ValueType getEnd() const noexcept { return end; }
  12071. /** Returns true if the range has a length of zero. */
  12072. inline bool isEmpty() const noexcept { return start == end; }
  12073. /** Changes the start position of the range, leaving the end position unchanged.
  12074. If the new start position is higher than the current end of the range, the end point
  12075. will be pushed along to equal it, leaving an empty range at the new position.
  12076. */
  12077. void setStart (const ValueType newStart) noexcept
  12078. {
  12079. start = newStart;
  12080. if (end < newStart)
  12081. end = newStart;
  12082. }
  12083. /** Returns a range with the same end as this one, but a different start.
  12084. If the new start position is higher than the current end of the range, the end point
  12085. will be pushed along to equal it, returning an empty range at the new position.
  12086. */
  12087. Range withStart (const ValueType newStart) const noexcept
  12088. {
  12089. return Range (newStart, jmax (newStart, end));
  12090. }
  12091. /** Returns a range with the same length as this one, but moved to have the given start position. */
  12092. Range movedToStartAt (const ValueType newStart) const noexcept
  12093. {
  12094. return Range (newStart, end + (newStart - start));
  12095. }
  12096. /** Changes the end position of the range, leaving the start unchanged.
  12097. If the new end position is below the current start of the range, the start point
  12098. will be pushed back to equal the new end point.
  12099. */
  12100. void setEnd (const ValueType newEnd) noexcept
  12101. {
  12102. end = newEnd;
  12103. if (newEnd < start)
  12104. start = newEnd;
  12105. }
  12106. /** Returns a range with the same start position as this one, but a different end.
  12107. If the new end position is below the current start of the range, the start point
  12108. will be pushed back to equal the new end point.
  12109. */
  12110. Range withEnd (const ValueType newEnd) const noexcept
  12111. {
  12112. return Range (jmin (start, newEnd), newEnd);
  12113. }
  12114. /** Returns a range with the same length as this one, but moved to have the given start position. */
  12115. Range movedToEndAt (const ValueType newEnd) const noexcept
  12116. {
  12117. return Range (start + (newEnd - end), newEnd);
  12118. }
  12119. /** Changes the length of the range.
  12120. Lengths less than zero are treated as zero.
  12121. */
  12122. void setLength (const ValueType newLength) noexcept
  12123. {
  12124. end = start + jmax (ValueType(), newLength);
  12125. }
  12126. /** Returns a range with the same start as this one, but a different length.
  12127. Lengths less than zero are treated as zero.
  12128. */
  12129. Range withLength (const ValueType newLength) const noexcept
  12130. {
  12131. return Range (start, start + newLength);
  12132. }
  12133. /** Adds an amount to the start and end of the range. */
  12134. inline const Range& operator+= (const ValueType amountToAdd) noexcept
  12135. {
  12136. start += amountToAdd;
  12137. end += amountToAdd;
  12138. return *this;
  12139. }
  12140. /** Subtracts an amount from the start and end of the range. */
  12141. inline const Range& operator-= (const ValueType amountToSubtract) noexcept
  12142. {
  12143. start -= amountToSubtract;
  12144. end -= amountToSubtract;
  12145. return *this;
  12146. }
  12147. /** Returns a range that is equal to this one with an amount added to its
  12148. start and end.
  12149. */
  12150. Range operator+ (const ValueType amountToAdd) const noexcept
  12151. {
  12152. return Range (start + amountToAdd, end + amountToAdd);
  12153. }
  12154. /** Returns a range that is equal to this one with the specified amount
  12155. subtracted from its start and end. */
  12156. Range operator- (const ValueType amountToSubtract) const noexcept
  12157. {
  12158. return Range (start - amountToSubtract, end - amountToSubtract);
  12159. }
  12160. bool operator== (const Range& other) const noexcept { return start == other.start && end == other.end; }
  12161. bool operator!= (const Range& other) const noexcept { return start != other.start || end != other.end; }
  12162. /** Returns true if the given position lies inside this range. */
  12163. bool contains (const ValueType position) const noexcept
  12164. {
  12165. return start <= position && position < end;
  12166. }
  12167. /** Returns the nearest value to the one supplied, which lies within the range. */
  12168. ValueType clipValue (const ValueType value) const noexcept
  12169. {
  12170. return jlimit (start, end, value);
  12171. }
  12172. /** Returns true if the given range lies entirely inside this range. */
  12173. bool contains (const Range& other) const noexcept
  12174. {
  12175. return start <= other.start && end >= other.end;
  12176. }
  12177. /** Returns true if the given range intersects this one. */
  12178. bool intersects (const Range& other) const noexcept
  12179. {
  12180. return other.start < end && start < other.end;
  12181. }
  12182. /** Returns the range that is the intersection of the two ranges, or an empty range
  12183. with an undefined start position if they don't overlap. */
  12184. Range getIntersectionWith (const Range& other) const noexcept
  12185. {
  12186. return Range (jmax (start, other.start),
  12187. jmin (end, other.end));
  12188. }
  12189. /** Returns the smallest range that contains both this one and the other one. */
  12190. Range getUnionWith (const Range& other) const noexcept
  12191. {
  12192. return Range (jmin (start, other.start),
  12193. jmax (end, other.end));
  12194. }
  12195. /** Returns a given range, after moving it forwards or backwards to fit it
  12196. within this range.
  12197. If the supplied range has a greater length than this one, the return value
  12198. will be this range.
  12199. Otherwise, if the supplied range is smaller than this one, the return value
  12200. will be the new range, shifted forwards or backwards so that it doesn't extend
  12201. beyond this one, but keeping its original length.
  12202. */
  12203. Range constrainRange (const Range& rangeToConstrain) const noexcept
  12204. {
  12205. const ValueType otherLen = rangeToConstrain.getLength();
  12206. return getLength() <= otherLen
  12207. ? *this
  12208. : rangeToConstrain.movedToStartAt (jlimit (start, end - otherLen, rangeToConstrain.getStart()));
  12209. }
  12210. private:
  12211. ValueType start, end;
  12212. };
  12213. #endif // __JUCE_RANGE_JUCEHEADER__
  12214. /*** End of inlined file: juce_Range.h ***/
  12215. /**
  12216. Holds a set of primitive values, storing them as a set of ranges.
  12217. This container acts like an array, but can efficiently hold large continguous
  12218. ranges of values. It's quite a specialised class, mostly useful for things
  12219. like keeping the set of selected rows in a listbox.
  12220. The type used as a template paramter must be an integer type, such as int, short,
  12221. int64, etc.
  12222. */
  12223. template <class Type>
  12224. class SparseSet
  12225. {
  12226. public:
  12227. /** Creates a new empty set. */
  12228. SparseSet()
  12229. {
  12230. }
  12231. /** Creates a copy of another SparseSet. */
  12232. SparseSet (const SparseSet<Type>& other)
  12233. : values (other.values)
  12234. {
  12235. }
  12236. /** Clears the set. */
  12237. void clear()
  12238. {
  12239. values.clear();
  12240. }
  12241. /** Checks whether the set is empty.
  12242. This is much quicker than using (size() == 0).
  12243. */
  12244. bool isEmpty() const noexcept
  12245. {
  12246. return values.size() == 0;
  12247. }
  12248. /** Returns the number of values in the set.
  12249. Because of the way the data is stored, this method can take longer if there
  12250. are a lot of items in the set. Use isEmpty() for a quick test of whether there
  12251. are any items.
  12252. */
  12253. Type size() const
  12254. {
  12255. Type total (0);
  12256. for (int i = 0; i < values.size(); i += 2)
  12257. total += values.getUnchecked (i + 1) - values.getUnchecked (i);
  12258. return total;
  12259. }
  12260. /** Returns one of the values in the set.
  12261. @param index the index of the value to retrieve, in the range 0 to (size() - 1).
  12262. @returns the value at this index, or 0 if it's out-of-range
  12263. */
  12264. Type operator[] (Type index) const
  12265. {
  12266. for (int i = 0; i < values.size(); i += 2)
  12267. {
  12268. const Type start (values.getUnchecked (i));
  12269. const Type len (values.getUnchecked (i + 1) - start);
  12270. if (index < len)
  12271. return start + index;
  12272. index -= len;
  12273. }
  12274. return Type();
  12275. }
  12276. /** Checks whether a particular value is in the set. */
  12277. bool contains (const Type valueToLookFor) const
  12278. {
  12279. for (int i = 0; i < values.size(); ++i)
  12280. if (valueToLookFor < values.getUnchecked(i))
  12281. return (i & 1) != 0;
  12282. return false;
  12283. }
  12284. /** Returns the number of contiguous blocks of values.
  12285. @see getRange
  12286. */
  12287. int getNumRanges() const noexcept
  12288. {
  12289. return values.size() >> 1;
  12290. }
  12291. /** Returns one of the contiguous ranges of values stored.
  12292. @param rangeIndex the index of the range to look up, between 0
  12293. and (getNumRanges() - 1)
  12294. @see getTotalRange
  12295. */
  12296. const Range<Type> getRange (const int rangeIndex) const
  12297. {
  12298. if (isPositiveAndBelow (rangeIndex, getNumRanges()))
  12299. return Range<Type> (values.getUnchecked (rangeIndex << 1),
  12300. values.getUnchecked ((rangeIndex << 1) + 1));
  12301. else
  12302. return Range<Type>();
  12303. }
  12304. /** Returns the range between the lowest and highest values in the set.
  12305. @see getRange
  12306. */
  12307. const Range<Type> getTotalRange() const
  12308. {
  12309. if (values.size() > 0)
  12310. {
  12311. jassert ((values.size() & 1) == 0);
  12312. return Range<Type> (values.getUnchecked (0),
  12313. values.getUnchecked (values.size() - 1));
  12314. }
  12315. return Range<Type>();
  12316. }
  12317. /** Adds a range of contiguous values to the set.
  12318. e.g. addRange (Range \<int\> (10, 14)) will add (10, 11, 12, 13) to the set.
  12319. */
  12320. void addRange (const Range<Type>& range)
  12321. {
  12322. jassert (range.getLength() >= 0);
  12323. if (range.getLength() > 0)
  12324. {
  12325. removeRange (range);
  12326. values.addUsingDefaultSort (range.getStart());
  12327. values.addUsingDefaultSort (range.getEnd());
  12328. simplify();
  12329. }
  12330. }
  12331. /** Removes a range of values from the set.
  12332. e.g. removeRange (Range\<int\> (10, 14)) will remove (10, 11, 12, 13) from the set.
  12333. */
  12334. void removeRange (const Range<Type>& rangeToRemove)
  12335. {
  12336. jassert (rangeToRemove.getLength() >= 0);
  12337. if (rangeToRemove.getLength() > 0
  12338. && values.size() > 0
  12339. && rangeToRemove.getStart() < values.getUnchecked (values.size() - 1)
  12340. && values.getUnchecked(0) < rangeToRemove.getEnd())
  12341. {
  12342. const bool onAtStart = contains (rangeToRemove.getStart() - 1);
  12343. const Type lastValue (jmin (rangeToRemove.getEnd(), values.getLast()));
  12344. const bool onAtEnd = contains (lastValue);
  12345. for (int i = values.size(); --i >= 0;)
  12346. {
  12347. if (values.getUnchecked(i) <= lastValue)
  12348. {
  12349. while (values.getUnchecked(i) >= rangeToRemove.getStart())
  12350. {
  12351. values.remove (i);
  12352. if (--i < 0)
  12353. break;
  12354. }
  12355. break;
  12356. }
  12357. }
  12358. if (onAtStart) values.addUsingDefaultSort (rangeToRemove.getStart());
  12359. if (onAtEnd) values.addUsingDefaultSort (lastValue);
  12360. simplify();
  12361. }
  12362. }
  12363. /** Does an XOR of the values in a given range. */
  12364. void invertRange (const Range<Type>& range)
  12365. {
  12366. SparseSet newItems;
  12367. newItems.addRange (range);
  12368. int i;
  12369. for (i = getNumRanges(); --i >= 0;)
  12370. newItems.removeRange (getRange (i));
  12371. removeRange (range);
  12372. for (i = newItems.getNumRanges(); --i >= 0;)
  12373. addRange (newItems.getRange(i));
  12374. }
  12375. /** Checks whether any part of a given range overlaps any part of this set. */
  12376. bool overlapsRange (const Range<Type>& range)
  12377. {
  12378. if (range.getLength() > 0)
  12379. {
  12380. for (int i = getNumRanges(); --i >= 0;)
  12381. {
  12382. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  12383. return false;
  12384. if (values.getUnchecked (i << 1) < range.getEnd())
  12385. return true;
  12386. }
  12387. }
  12388. return false;
  12389. }
  12390. /** Checks whether the whole of a given range is contained within this one. */
  12391. bool containsRange (const Range<Type>& range)
  12392. {
  12393. if (range.getLength() > 0)
  12394. {
  12395. for (int i = getNumRanges(); --i >= 0;)
  12396. {
  12397. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  12398. return false;
  12399. if (values.getUnchecked (i << 1) <= range.getStart()
  12400. && range.getEnd() <= values.getUnchecked ((i << 1) + 1))
  12401. return true;
  12402. }
  12403. }
  12404. return false;
  12405. }
  12406. bool operator== (const SparseSet<Type>& other) noexcept
  12407. {
  12408. return values == other.values;
  12409. }
  12410. bool operator!= (const SparseSet<Type>& other) noexcept
  12411. {
  12412. return values != other.values;
  12413. }
  12414. private:
  12415. // alternating start/end values of ranges of values that are present.
  12416. Array<Type, DummyCriticalSection> values;
  12417. void simplify()
  12418. {
  12419. jassert ((values.size() & 1) == 0);
  12420. for (int i = values.size(); --i > 0;)
  12421. if (values.getUnchecked(i) == values.getUnchecked (i - 1))
  12422. values.removeRange (--i, 2);
  12423. }
  12424. };
  12425. #endif // __JUCE_SPARSESET_JUCEHEADER__
  12426. /*** End of inlined file: juce_SparseSet.h ***/
  12427. #endif
  12428. #ifndef __JUCE_VALUE_JUCEHEADER__
  12429. /*** Start of inlined file: juce_Value.h ***/
  12430. #ifndef __JUCE_VALUE_JUCEHEADER__
  12431. #define __JUCE_VALUE_JUCEHEADER__
  12432. /*** Start of inlined file: juce_AsyncUpdater.h ***/
  12433. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  12434. #define __JUCE_ASYNCUPDATER_JUCEHEADER__
  12435. /*** Start of inlined file: juce_CallbackMessage.h ***/
  12436. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  12437. #define __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  12438. /*** Start of inlined file: juce_Message.h ***/
  12439. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  12440. #define __JUCE_MESSAGE_JUCEHEADER__
  12441. class MessageListener;
  12442. class MessageManager;
  12443. /** The base class for objects that can be delivered to a MessageListener.
  12444. The simplest Message object contains a few integer and pointer parameters
  12445. that the user can set, and this is enough for a lot of purposes. For passing more
  12446. complex data, subclasses of Message can also be used.
  12447. @see MessageListener, MessageManager, ActionListener, ChangeListener
  12448. */
  12449. class JUCE_API Message : public ReferenceCountedObject
  12450. {
  12451. public:
  12452. /** Creates an uninitialised message.
  12453. The class's variables will also be left uninitialised.
  12454. */
  12455. Message() noexcept;
  12456. /** Creates a message object, filling in the member variables.
  12457. The corresponding public member variables will be set from the parameters
  12458. passed in.
  12459. */
  12460. Message (int intParameter1,
  12461. int intParameter2,
  12462. int intParameter3,
  12463. void* pointerParameter) noexcept;
  12464. /** Destructor. */
  12465. virtual ~Message();
  12466. // These values can be used for carrying simple data that the application needs to
  12467. // pass around. For more complex messages, just create a subclass.
  12468. int intParameter1; /**< user-defined integer value. */
  12469. int intParameter2; /**< user-defined integer value. */
  12470. int intParameter3; /**< user-defined integer value. */
  12471. void* pointerParameter; /**< user-defined pointer value. */
  12472. /** A typedef for pointers to messages. */
  12473. typedef ReferenceCountedObjectPtr <Message> Ptr;
  12474. private:
  12475. friend class MessageListener;
  12476. friend class MessageManager;
  12477. MessageListener* messageRecipient;
  12478. // Avoid the leak-detector because for plugins, the host can unload our DLL with undelivered
  12479. // messages still in the system event queue. These aren't harmful, but can cause annoying assertions.
  12480. JUCE_DECLARE_NON_COPYABLE (Message);
  12481. };
  12482. #endif // __JUCE_MESSAGE_JUCEHEADER__
  12483. /*** End of inlined file: juce_Message.h ***/
  12484. /**
  12485. A message that calls a custom function when it gets delivered.
  12486. You can use this class to fire off actions that you want to be performed later
  12487. on the message thread.
  12488. Unlike other Message objects, these don't get sent to a MessageListener, you
  12489. just call the post() method to send them, and when they arrive, your
  12490. messageCallback() method will automatically be invoked.
  12491. Always create an instance of a CallbackMessage on the heap, as it will be
  12492. deleted automatically after the message has been delivered.
  12493. @see MessageListener, MessageManager, ActionListener, ChangeListener
  12494. */
  12495. class JUCE_API CallbackMessage : public Message
  12496. {
  12497. public:
  12498. CallbackMessage() noexcept;
  12499. /** Destructor. */
  12500. ~CallbackMessage();
  12501. /** Called when the message is delivered.
  12502. You should implement this method and make it do whatever action you want
  12503. to perform.
  12504. Note that like all other messages, this object will be deleted immediately
  12505. after this method has been invoked.
  12506. */
  12507. virtual void messageCallback() = 0;
  12508. /** Instead of sending this message to a MessageListener, just call this method
  12509. to post it to the event queue.
  12510. After you've called this, this object will belong to the MessageManager,
  12511. which will delete it later. So make sure you don't delete the object yourself,
  12512. call post() more than once, or call post() on a stack-based obect!
  12513. */
  12514. void post();
  12515. private:
  12516. // Avoid the leak-detector because for plugins, the host can unload our DLL with undelivered
  12517. // messages still in the system event queue. These aren't harmful, but can cause annoying assertions.
  12518. JUCE_DECLARE_NON_COPYABLE (CallbackMessage);
  12519. };
  12520. #endif // __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  12521. /*** End of inlined file: juce_CallbackMessage.h ***/
  12522. /**
  12523. Has a callback method that is triggered asynchronously.
  12524. This object allows an asynchronous callback function to be triggered, for
  12525. tasks such as coalescing multiple updates into a single callback later on.
  12526. Basically, one or more calls to the triggerAsyncUpdate() will result in the
  12527. message thread calling handleAsyncUpdate() as soon as it can.
  12528. */
  12529. class JUCE_API AsyncUpdater
  12530. {
  12531. public:
  12532. /** Creates an AsyncUpdater object. */
  12533. AsyncUpdater();
  12534. /** Destructor.
  12535. If there are any pending callbacks when the object is deleted, these are lost.
  12536. */
  12537. virtual ~AsyncUpdater();
  12538. /** Causes the callback to be triggered at a later time.
  12539. This method returns immediately, having made sure that a callback
  12540. to the handleAsyncUpdate() method will occur as soon as possible.
  12541. If an update callback is already pending but hasn't happened yet, calls
  12542. to this method will be ignored.
  12543. It's thread-safe to call this method from any number of threads without
  12544. needing to worry about locking.
  12545. */
  12546. void triggerAsyncUpdate();
  12547. /** This will stop any pending updates from happening.
  12548. If called after triggerAsyncUpdate() and before the handleAsyncUpdate()
  12549. callback happens, this will cancel the handleAsyncUpdate() callback.
  12550. Note that this method simply cancels the next callback - if a callback is already
  12551. in progress on a different thread, this won't block until it finishes, so there's
  12552. no guarantee that the callback isn't still running when you return from
  12553. */
  12554. void cancelPendingUpdate() noexcept;
  12555. /** If an update has been triggered and is pending, this will invoke it
  12556. synchronously.
  12557. Use this as a kind of "flush" operation - if an update is pending, the
  12558. handleAsyncUpdate() method will be called immediately; if no update is
  12559. pending, then nothing will be done.
  12560. Because this may invoke the callback, this method must only be called on
  12561. the main event thread.
  12562. */
  12563. void handleUpdateNowIfNeeded();
  12564. /** Returns true if there's an update callback in the pipeline. */
  12565. bool isUpdatePending() const noexcept;
  12566. /** Called back to do whatever your class needs to do.
  12567. This method is called by the message thread at the next convenient time
  12568. after the triggerAsyncUpdate() method has been called.
  12569. */
  12570. virtual void handleAsyncUpdate() = 0;
  12571. private:
  12572. ReferenceCountedObjectPtr<CallbackMessage> message;
  12573. Atomic<int>& getDeliveryFlag() const noexcept;
  12574. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AsyncUpdater);
  12575. };
  12576. #endif // __JUCE_ASYNCUPDATER_JUCEHEADER__
  12577. /*** End of inlined file: juce_AsyncUpdater.h ***/
  12578. /*** Start of inlined file: juce_ListenerList.h ***/
  12579. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  12580. #define __JUCE_LISTENERLIST_JUCEHEADER__
  12581. /**
  12582. Holds a set of objects and can invoke a member function callback on each object
  12583. in the set with a single call.
  12584. Use a ListenerList to manage a set of objects which need a callback, and you
  12585. can invoke a member function by simply calling call() or callChecked().
  12586. E.g.
  12587. @code
  12588. class MyListenerType
  12589. {
  12590. public:
  12591. void myCallbackMethod (int foo, bool bar);
  12592. };
  12593. ListenerList <MyListenerType> listeners;
  12594. listeners.add (someCallbackObjects...);
  12595. // This will invoke myCallbackMethod (1234, true) on each of the objects
  12596. // in the list...
  12597. listeners.call (&MyListenerType::myCallbackMethod, 1234, true);
  12598. @endcode
  12599. If you add or remove listeners from the list during one of the callbacks - i.e. while
  12600. it's in the middle of iterating the listeners, then it's guaranteed that no listeners
  12601. will be mistakenly called after they've been removed, but it may mean that some of the
  12602. listeners could be called more than once, or not at all, depending on the list's order.
  12603. Sometimes, there's a chance that invoking one of the callbacks might result in the
  12604. list itself being deleted while it's still iterating - to survive this situation, you can
  12605. use callChecked() instead of call(), passing it a local object to act as a "BailOutChecker".
  12606. The BailOutChecker must implement a method of the form "bool shouldBailOut()", and
  12607. the list will check this after each callback to determine whether it should abort the
  12608. operation. For an example of a bail-out checker, see the Component::BailOutChecker class,
  12609. which can be used to check when a Component has been deleted. See also
  12610. ListenerList::DummyBailOutChecker, which is a dummy checker that always returns false.
  12611. */
  12612. template <class ListenerClass,
  12613. class ArrayType = Array <ListenerClass*> >
  12614. class ListenerList
  12615. {
  12616. // Horrible macros required to support VC6/7..
  12617. #ifndef DOXYGEN
  12618. #if JUCE_VC8_OR_EARLIER
  12619. #define LL_TEMPLATE(a) typename P##a, typename Q##a
  12620. #define LL_PARAM(a) Q##a& param##a
  12621. #else
  12622. #define LL_TEMPLATE(a) typename P##a
  12623. #define LL_PARAM(a) PARAMETER_TYPE(P##a) param##a
  12624. #endif
  12625. #endif
  12626. public:
  12627. /** Creates an empty list. */
  12628. ListenerList()
  12629. {
  12630. }
  12631. /** Destructor. */
  12632. ~ListenerList()
  12633. {
  12634. }
  12635. /** Adds a listener to the list.
  12636. A listener can only be added once, so if the listener is already in the list,
  12637. this method has no effect.
  12638. @see remove
  12639. */
  12640. void add (ListenerClass* const listenerToAdd)
  12641. {
  12642. // Listeners can't be null pointers!
  12643. jassert (listenerToAdd != nullptr);
  12644. if (listenerToAdd != nullptr)
  12645. listeners.addIfNotAlreadyThere (listenerToAdd);
  12646. }
  12647. /** Removes a listener from the list.
  12648. If the listener wasn't in the list, this has no effect.
  12649. */
  12650. void remove (ListenerClass* const listenerToRemove)
  12651. {
  12652. // Listeners can't be null pointers!
  12653. jassert (listenerToRemove != nullptr);
  12654. listeners.removeValue (listenerToRemove);
  12655. }
  12656. /** Returns the number of registered listeners. */
  12657. int size() const noexcept
  12658. {
  12659. return listeners.size();
  12660. }
  12661. /** Returns true if any listeners are registered. */
  12662. bool isEmpty() const noexcept
  12663. {
  12664. return listeners.size() == 0;
  12665. }
  12666. /** Clears the list. */
  12667. void clear()
  12668. {
  12669. listeners.clear();
  12670. }
  12671. /** Returns true if the specified listener has been added to the list. */
  12672. bool contains (ListenerClass* const listener) const noexcept
  12673. {
  12674. return listeners.contains (listener);
  12675. }
  12676. /** Calls a member function on each listener in the list, with no parameters. */
  12677. void call (void (ListenerClass::*callbackFunction) ())
  12678. {
  12679. callChecked (static_cast <const DummyBailOutChecker&> (DummyBailOutChecker()), callbackFunction);
  12680. }
  12681. /** Calls a member function on each listener in the list, with no parameters and a bail-out-checker.
  12682. See the class description for info about writing a bail-out checker. */
  12683. template <class BailOutCheckerType>
  12684. void callChecked (const BailOutCheckerType& bailOutChecker,
  12685. void (ListenerClass::*callbackFunction) ())
  12686. {
  12687. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12688. (iter.getListener()->*callbackFunction) ();
  12689. }
  12690. /** Calls a member function on each listener in the list, with 1 parameter. */
  12691. template <LL_TEMPLATE(1)>
  12692. void call (void (ListenerClass::*callbackFunction) (P1), LL_PARAM(1))
  12693. {
  12694. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  12695. (iter.getListener()->*callbackFunction) (param1);
  12696. }
  12697. /** Calls a member function on each listener in the list, with one parameter and a bail-out-checker.
  12698. See the class description for info about writing a bail-out checker. */
  12699. template <class BailOutCheckerType, LL_TEMPLATE(1)>
  12700. void callChecked (const BailOutCheckerType& bailOutChecker,
  12701. void (ListenerClass::*callbackFunction) (P1),
  12702. LL_PARAM(1))
  12703. {
  12704. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12705. (iter.getListener()->*callbackFunction) (param1);
  12706. }
  12707. /** Calls a member function on each listener in the list, with 2 parameters. */
  12708. template <LL_TEMPLATE(1), LL_TEMPLATE(2)>
  12709. void call (void (ListenerClass::*callbackFunction) (P1, P2),
  12710. LL_PARAM(1), LL_PARAM(2))
  12711. {
  12712. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  12713. (iter.getListener()->*callbackFunction) (param1, param2);
  12714. }
  12715. /** Calls a member function on each listener in the list, with 2 parameters and a bail-out-checker.
  12716. See the class description for info about writing a bail-out checker. */
  12717. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2)>
  12718. void callChecked (const BailOutCheckerType& bailOutChecker,
  12719. void (ListenerClass::*callbackFunction) (P1, P2),
  12720. LL_PARAM(1), LL_PARAM(2))
  12721. {
  12722. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12723. (iter.getListener()->*callbackFunction) (param1, param2);
  12724. }
  12725. /** Calls a member function on each listener in the list, with 3 parameters. */
  12726. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  12727. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3),
  12728. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  12729. {
  12730. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  12731. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  12732. }
  12733. /** Calls a member function on each listener in the list, with 3 parameters and a bail-out-checker.
  12734. See the class description for info about writing a bail-out checker. */
  12735. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  12736. void callChecked (const BailOutCheckerType& bailOutChecker,
  12737. void (ListenerClass::*callbackFunction) (P1, P2, P3),
  12738. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  12739. {
  12740. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12741. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  12742. }
  12743. /** Calls a member function on each listener in the list, with 4 parameters. */
  12744. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  12745. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  12746. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  12747. {
  12748. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  12749. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  12750. }
  12751. /** Calls a member function on each listener in the list, with 4 parameters and a bail-out-checker.
  12752. See the class description for info about writing a bail-out checker. */
  12753. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  12754. void callChecked (const BailOutCheckerType& bailOutChecker,
  12755. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  12756. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  12757. {
  12758. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12759. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  12760. }
  12761. /** Calls a member function on each listener in the list, with 5 parameters. */
  12762. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  12763. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  12764. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  12765. {
  12766. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  12767. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  12768. }
  12769. /** Calls a member function on each listener in the list, with 5 parameters and a bail-out-checker.
  12770. See the class description for info about writing a bail-out checker. */
  12771. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  12772. void callChecked (const BailOutCheckerType& bailOutChecker,
  12773. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  12774. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  12775. {
  12776. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12777. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  12778. }
  12779. /** A dummy bail-out checker that always returns false.
  12780. See the ListenerList notes for more info about bail-out checkers.
  12781. */
  12782. class DummyBailOutChecker
  12783. {
  12784. public:
  12785. inline bool shouldBailOut() const noexcept { return false; }
  12786. };
  12787. /** Iterates the listeners in a ListenerList. */
  12788. template <class BailOutCheckerType, class ListType>
  12789. class Iterator
  12790. {
  12791. public:
  12792. Iterator (const ListType& list_)
  12793. : list (list_), index (list_.size())
  12794. {}
  12795. ~Iterator() {}
  12796. bool next()
  12797. {
  12798. if (index <= 0)
  12799. return false;
  12800. const int listSize = list.size();
  12801. if (--index < listSize)
  12802. return true;
  12803. index = listSize - 1;
  12804. return index >= 0;
  12805. }
  12806. bool next (const BailOutCheckerType& bailOutChecker)
  12807. {
  12808. return (! bailOutChecker.shouldBailOut()) && next();
  12809. }
  12810. typename ListType::ListenerType* getListener() const noexcept
  12811. {
  12812. return list.getListeners().getUnchecked (index);
  12813. }
  12814. private:
  12815. const ListType& list;
  12816. int index;
  12817. JUCE_DECLARE_NON_COPYABLE (Iterator);
  12818. };
  12819. typedef ListenerList<ListenerClass, ArrayType> ThisType;
  12820. typedef ListenerClass ListenerType;
  12821. const ArrayType& getListeners() const noexcept { return listeners; }
  12822. private:
  12823. ArrayType listeners;
  12824. JUCE_DECLARE_NON_COPYABLE (ListenerList);
  12825. #undef LL_TEMPLATE
  12826. #undef LL_PARAM
  12827. };
  12828. #endif // __JUCE_LISTENERLIST_JUCEHEADER__
  12829. /*** End of inlined file: juce_ListenerList.h ***/
  12830. /**
  12831. Represents a shared variant value.
  12832. A Value object contains a reference to a var object, and can get and set its value.
  12833. Listeners can be attached to be told when the value is changed.
  12834. The Value class is a wrapper around a shared, reference-counted underlying data
  12835. object - this means that multiple Value objects can all refer to the same piece of
  12836. data, allowing all of them to be notified when any of them changes it.
  12837. When you create a Value with its default constructor, it acts as a wrapper around a
  12838. simple var object, but by creating a Value that refers to a custom subclass of ValueSource,
  12839. you can map the Value onto any kind of underlying data.
  12840. */
  12841. class JUCE_API Value
  12842. {
  12843. public:
  12844. /** Creates an empty Value, containing a void var. */
  12845. Value();
  12846. /** Creates a Value that refers to the same value as another one.
  12847. Note that this doesn't make a copy of the other value - both this and the other
  12848. Value will share the same underlying value, so that when either one alters it, both
  12849. will see it change.
  12850. */
  12851. Value (const Value& other);
  12852. /** Creates a Value that is set to the specified value. */
  12853. explicit Value (const var& initialValue);
  12854. /** Destructor. */
  12855. ~Value();
  12856. /** Returns the current value. */
  12857. var getValue() const;
  12858. /** Returns the current value. */
  12859. operator var() const;
  12860. /** Returns the value as a string.
  12861. This is alternative to writing things like "myValue.getValue().toString()".
  12862. */
  12863. String toString() const;
  12864. /** Sets the current value.
  12865. You can also use operator= to set the value.
  12866. If there are any listeners registered, they will be notified of the
  12867. change asynchronously.
  12868. */
  12869. void setValue (const var& newValue);
  12870. /** Sets the current value.
  12871. This is the same as calling setValue().
  12872. If there are any listeners registered, they will be notified of the
  12873. change asynchronously.
  12874. */
  12875. Value& operator= (const var& newValue);
  12876. /** Makes this object refer to the same underlying ValueSource as another one.
  12877. Once this object has been connected to another one, changing either one
  12878. will update the other.
  12879. Existing listeners will still be registered after you call this method, and
  12880. they'll continue to receive messages when the new value changes.
  12881. */
  12882. void referTo (const Value& valueToReferTo);
  12883. /** Returns true if this value and the other one are references to the same value.
  12884. */
  12885. bool refersToSameSourceAs (const Value& other) const;
  12886. /** Compares two values.
  12887. This is a compare-by-value comparison, so is effectively the same as
  12888. saying (this->getValue() == other.getValue()).
  12889. */
  12890. bool operator== (const Value& other) const;
  12891. /** Compares two values.
  12892. This is a compare-by-value comparison, so is effectively the same as
  12893. saying (this->getValue() != other.getValue()).
  12894. */
  12895. bool operator!= (const Value& other) const;
  12896. /** Receives callbacks when a Value object changes.
  12897. @see Value::addListener
  12898. */
  12899. class JUCE_API Listener
  12900. {
  12901. public:
  12902. Listener() {}
  12903. virtual ~Listener() {}
  12904. /** Called when a Value object is changed.
  12905. Note that the Value object passed as a parameter may not be exactly the same
  12906. object that you registered the listener with - it might be a copy that refers
  12907. to the same underlying ValueSource. To find out, you can call Value::refersToSameSourceAs().
  12908. */
  12909. virtual void valueChanged (Value& value) = 0;
  12910. };
  12911. /** Adds a listener to receive callbacks when the value changes.
  12912. The listener is added to this specific Value object, and not to the shared
  12913. object that it refers to. When this object is deleted, all the listeners will
  12914. be lost, even if other references to the same Value still exist. So when you're
  12915. adding a listener, make sure that you add it to a ValueTree instance that will last
  12916. for as long as you need the listener. In general, you'd never want to add a listener
  12917. to a local stack-based ValueTree, but more likely to one that's a member variable.
  12918. @see removeListener
  12919. */
  12920. void addListener (Listener* listener);
  12921. /** Removes a listener that was previously added with addListener(). */
  12922. void removeListener (Listener* listener);
  12923. /**
  12924. Used internally by the Value class as the base class for its shared value objects.
  12925. The Value class is essentially a reference-counted pointer to a shared instance
  12926. of a ValueSource object. If you're feeling adventurous, you can create your own custom
  12927. ValueSource classes to allow Value objects to represent your own custom data items.
  12928. */
  12929. class JUCE_API ValueSource : public SingleThreadedReferenceCountedObject,
  12930. public AsyncUpdater
  12931. {
  12932. public:
  12933. ValueSource();
  12934. virtual ~ValueSource();
  12935. /** Returns the current value of this object. */
  12936. virtual var getValue() const = 0;
  12937. /** Changes the current value.
  12938. This must also trigger a change message if the value actually changes.
  12939. */
  12940. virtual void setValue (const var& newValue) = 0;
  12941. /** Delivers a change message to all the listeners that are registered with
  12942. this value.
  12943. If dispatchSynchronously is true, the method will call all the listeners
  12944. before returning; otherwise it'll dispatch a message and make the call later.
  12945. */
  12946. void sendChangeMessage (bool dispatchSynchronously);
  12947. protected:
  12948. friend class Value;
  12949. SortedSet <Value*> valuesWithListeners;
  12950. void handleAsyncUpdate();
  12951. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ValueSource);
  12952. };
  12953. /** Creates a Value object that uses this valueSource object as its underlying data. */
  12954. explicit Value (ValueSource* valueSource);
  12955. /** Returns the ValueSource that this value is referring to. */
  12956. ValueSource& getValueSource() noexcept { return *value; }
  12957. private:
  12958. friend class ValueSource;
  12959. ReferenceCountedObjectPtr <ValueSource> value;
  12960. ListenerList <Listener> listeners;
  12961. void callListeners();
  12962. // This is disallowed to avoid confusion about whether it should
  12963. // do a by-value or by-reference copy.
  12964. Value& operator= (const Value& other);
  12965. };
  12966. /** Writes a Value to an OutputStream as a UTF8 string. */
  12967. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value);
  12968. /** This typedef is just for compatibility with old code - newer code should use the Value::Listener class directly. */
  12969. typedef Value::Listener ValueListener;
  12970. #endif // __JUCE_VALUE_JUCEHEADER__
  12971. /*** End of inlined file: juce_Value.h ***/
  12972. #endif
  12973. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  12974. /*** Start of inlined file: juce_ValueTree.h ***/
  12975. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  12976. #define __JUCE_VALUETREE_JUCEHEADER__
  12977. /*** Start of inlined file: juce_UndoManager.h ***/
  12978. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  12979. #define __JUCE_UNDOMANAGER_JUCEHEADER__
  12980. /*** Start of inlined file: juce_ChangeBroadcaster.h ***/
  12981. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  12982. #define __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  12983. /*** Start of inlined file: juce_ChangeListener.h ***/
  12984. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  12985. #define __JUCE_CHANGELISTENER_JUCEHEADER__
  12986. class ChangeBroadcaster;
  12987. /**
  12988. Receives change event callbacks that are sent out by a ChangeBroadcaster.
  12989. A ChangeBroadcaster keeps a set of listeners to which it broadcasts a message when
  12990. the ChangeBroadcaster::sendChangeMessage() method is called. A subclass of
  12991. ChangeListener is used to receive these callbacks.
  12992. Note that the major difference between an ActionListener and a ChangeListener
  12993. is that for a ChangeListener, multiple changes will be coalesced into fewer
  12994. callbacks, but ActionListeners perform one callback for every event posted.
  12995. @see ChangeBroadcaster, ActionListener
  12996. */
  12997. class JUCE_API ChangeListener
  12998. {
  12999. public:
  13000. /** Destructor. */
  13001. virtual ~ChangeListener() {}
  13002. /** Your subclass should implement this method to receive the callback.
  13003. @param source the ChangeBroadcaster that triggered the callback.
  13004. */
  13005. virtual void changeListenerCallback (ChangeBroadcaster* source) = 0;
  13006. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  13007. // This method's signature has changed to take a ChangeBroadcaster parameter - please update your code!
  13008. private: virtual int changeListenerCallback (void*) { return 0; }
  13009. #endif
  13010. };
  13011. #endif // __JUCE_CHANGELISTENER_JUCEHEADER__
  13012. /*** End of inlined file: juce_ChangeListener.h ***/
  13013. /**
  13014. Holds a list of ChangeListeners, and sends messages to them when instructed.
  13015. @see ChangeListener
  13016. */
  13017. class JUCE_API ChangeBroadcaster
  13018. {
  13019. public:
  13020. /** Creates an ChangeBroadcaster. */
  13021. ChangeBroadcaster() noexcept;
  13022. /** Destructor. */
  13023. virtual ~ChangeBroadcaster();
  13024. /** Registers a listener to receive change callbacks from this broadcaster.
  13025. Trying to add a listener that's already on the list will have no effect.
  13026. */
  13027. void addChangeListener (ChangeListener* listener);
  13028. /** Unregisters a listener from the list.
  13029. If the listener isn't on the list, this won't have any effect.
  13030. */
  13031. void removeChangeListener (ChangeListener* listener);
  13032. /** Removes all listeners from the list. */
  13033. void removeAllChangeListeners();
  13034. /** Causes an asynchronous change message to be sent to all the registered listeners.
  13035. The message will be delivered asynchronously by the main message thread, so this
  13036. method will return immediately. To call the listeners synchronously use
  13037. sendSynchronousChangeMessage().
  13038. */
  13039. void sendChangeMessage();
  13040. /** Sends a synchronous change message to all the registered listeners.
  13041. This will immediately call all the listeners that are registered. For thread-safety
  13042. reasons, you must only call this method on the main message thread.
  13043. @see dispatchPendingMessages
  13044. */
  13045. void sendSynchronousChangeMessage();
  13046. /** If a change message has been sent but not yet dispatched, this will call
  13047. sendSynchronousChangeMessage() to make the callback immediately.
  13048. For thread-safety reasons, you must only call this method on the main message thread.
  13049. */
  13050. void dispatchPendingMessages();
  13051. private:
  13052. class ChangeBroadcasterCallback : public AsyncUpdater
  13053. {
  13054. public:
  13055. ChangeBroadcasterCallback();
  13056. void handleAsyncUpdate();
  13057. ChangeBroadcaster* owner;
  13058. };
  13059. friend class ChangeBroadcasterCallback;
  13060. ChangeBroadcasterCallback callback;
  13061. ListenerList <ChangeListener> changeListeners;
  13062. void callListeners();
  13063. JUCE_DECLARE_NON_COPYABLE (ChangeBroadcaster);
  13064. };
  13065. #endif // __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  13066. /*** End of inlined file: juce_ChangeBroadcaster.h ***/
  13067. /*** Start of inlined file: juce_UndoableAction.h ***/
  13068. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  13069. #define __JUCE_UNDOABLEACTION_JUCEHEADER__
  13070. /**
  13071. Used by the UndoManager class to store an action which can be done
  13072. and undone.
  13073. @see UndoManager
  13074. */
  13075. class JUCE_API UndoableAction
  13076. {
  13077. protected:
  13078. /** Creates an action. */
  13079. UndoableAction() noexcept {}
  13080. public:
  13081. /** Destructor. */
  13082. virtual ~UndoableAction() {}
  13083. /** Overridden by a subclass to perform the action.
  13084. This method is called by the UndoManager, and shouldn't be used directly by
  13085. applications.
  13086. Be careful not to make any calls in a perform() method that could call
  13087. recursively back into the UndoManager::perform() method
  13088. @returns true if the action could be performed.
  13089. @see UndoManager::perform
  13090. */
  13091. virtual bool perform() = 0;
  13092. /** Overridden by a subclass to undo the action.
  13093. This method is called by the UndoManager, and shouldn't be used directly by
  13094. applications.
  13095. Be careful not to make any calls in an undo() method that could call
  13096. recursively back into the UndoManager::perform() method
  13097. @returns true if the action could be undone without any errors.
  13098. @see UndoManager::perform
  13099. */
  13100. virtual bool undo() = 0;
  13101. /** Returns a value to indicate how much memory this object takes up.
  13102. Because the UndoManager keeps a list of UndoableActions, this is used
  13103. to work out how much space each one will take up, so that the UndoManager
  13104. can work out how many to keep.
  13105. The default value returned here is 10 - units are arbitrary and
  13106. don't have to be accurate.
  13107. @see UndoManager::getNumberOfUnitsTakenUpByStoredCommands,
  13108. UndoManager::setMaxNumberOfStoredUnits
  13109. */
  13110. virtual int getSizeInUnits() { return 10; }
  13111. /** Allows multiple actions to be coalesced into a single action object, to reduce storage space.
  13112. If possible, this method should create and return a single action that does the same job as
  13113. this one followed by the supplied action.
  13114. If it's not possible to merge the two actions, the method should return zero.
  13115. */
  13116. virtual UndoableAction* createCoalescedAction (UndoableAction* nextAction) { (void) nextAction; return nullptr; }
  13117. };
  13118. #endif // __JUCE_UNDOABLEACTION_JUCEHEADER__
  13119. /*** End of inlined file: juce_UndoableAction.h ***/
  13120. /**
  13121. Manages a list of undo/redo commands.
  13122. An UndoManager object keeps a list of past actions and can use these actions
  13123. to move backwards and forwards through an undo history.
  13124. To use it, create subclasses of UndoableAction which perform all the
  13125. actions you need, then when you need to actually perform an action, create one
  13126. and pass it to the UndoManager's perform() method.
  13127. The manager also uses the concept of 'transactions' to group the actions
  13128. together - all actions performed between calls to beginNewTransaction() are
  13129. grouped together and are all undone/redone as a group.
  13130. The UndoManager is a ChangeBroadcaster, so listeners can register to be told
  13131. when actions are performed or undone.
  13132. @see UndoableAction
  13133. */
  13134. class JUCE_API UndoManager : public ChangeBroadcaster
  13135. {
  13136. public:
  13137. /** Creates an UndoManager.
  13138. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  13139. to indicate how much storage it takes up
  13140. (UndoableAction::getSizeInUnits()), so this
  13141. lets you specify the maximum total number of
  13142. units that the undomanager is allowed to
  13143. keep in memory before letting the older actions
  13144. drop off the end of the list.
  13145. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  13146. that will be kept, even if this involves exceeding
  13147. the amount of space specified in maxNumberOfUnitsToKeep
  13148. */
  13149. UndoManager (int maxNumberOfUnitsToKeep = 30000,
  13150. int minimumTransactionsToKeep = 30);
  13151. /** Destructor. */
  13152. ~UndoManager();
  13153. /** Deletes all stored actions in the list. */
  13154. void clearUndoHistory();
  13155. /** Returns the current amount of space to use for storing UndoableAction objects.
  13156. @see setMaxNumberOfStoredUnits
  13157. */
  13158. int getNumberOfUnitsTakenUpByStoredCommands() const;
  13159. /** Sets the amount of space that can be used for storing UndoableAction objects.
  13160. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  13161. to indicate how much storage it takes up
  13162. (UndoableAction::getSizeInUnits()), so this
  13163. lets you specify the maximum total number of
  13164. units that the undomanager is allowed to
  13165. keep in memory before letting the older actions
  13166. drop off the end of the list.
  13167. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  13168. that will be kept, even if this involves exceeding
  13169. the amount of space specified in maxNumberOfUnitsToKeep
  13170. @see getNumberOfUnitsTakenUpByStoredCommands
  13171. */
  13172. void setMaxNumberOfStoredUnits (int maxNumberOfUnitsToKeep,
  13173. int minimumTransactionsToKeep);
  13174. /** Performs an action and adds it to the undo history list.
  13175. @param action the action to perform - this will be deleted by the UndoManager
  13176. when no longer needed
  13177. @param actionName if this string is non-empty, the current transaction will be
  13178. given this name; if it's empty, the current transaction name will
  13179. be left unchanged. See setCurrentTransactionName()
  13180. @returns true if the command succeeds - see UndoableAction::perform
  13181. @see beginNewTransaction
  13182. */
  13183. bool perform (UndoableAction* action,
  13184. const String& actionName = String::empty);
  13185. /** Starts a new group of actions that together will be treated as a single transaction.
  13186. All actions that are passed to the perform() method between calls to this
  13187. method are grouped together and undone/redone together by a single call to
  13188. undo() or redo().
  13189. @param actionName a description of the transaction that is about to be
  13190. performed
  13191. */
  13192. void beginNewTransaction (const String& actionName = String::empty);
  13193. /** Changes the name stored for the current transaction.
  13194. Each transaction is given a name when the beginNewTransaction() method is
  13195. called, but this can be used to change that name without starting a new
  13196. transaction.
  13197. */
  13198. void setCurrentTransactionName (const String& newName);
  13199. /** Returns true if there's at least one action in the list to undo.
  13200. @see getUndoDescription, undo, canRedo
  13201. */
  13202. bool canUndo() const;
  13203. /** Returns the description of the transaction that would be next to get undone.
  13204. The description returned is the one that was passed into beginNewTransaction
  13205. before the set of actions was performed.
  13206. @see undo
  13207. */
  13208. String getUndoDescription() const;
  13209. /** Tries to roll-back the last transaction.
  13210. @returns true if the transaction can be undone, and false if it fails, or
  13211. if there aren't any transactions to undo
  13212. */
  13213. bool undo();
  13214. /** Tries to roll-back any actions that were added to the current transaction.
  13215. This will perform an undo() only if there are some actions in the undo list
  13216. that were added after the last call to beginNewTransaction().
  13217. This is useful because it lets you call beginNewTransaction(), then
  13218. perform an operation which may or may not actually perform some actions, and
  13219. then call this method to get rid of any actions that might have been done
  13220. without it rolling back the previous transaction if nothing was actually
  13221. done.
  13222. @returns true if any actions were undone.
  13223. */
  13224. bool undoCurrentTransactionOnly();
  13225. /** Returns a list of the UndoableAction objects that have been performed during the
  13226. transaction that is currently open.
  13227. Effectively, this is the list of actions that would be undone if undoCurrentTransactionOnly()
  13228. were to be called now.
  13229. The first item in the list is the earliest action performed.
  13230. */
  13231. void getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const;
  13232. /** Returns the number of UndoableAction objects that have been performed during the
  13233. transaction that is currently open.
  13234. @see getActionsInCurrentTransaction
  13235. */
  13236. int getNumActionsInCurrentTransaction() const;
  13237. /** Returns true if there's at least one action in the list to redo.
  13238. @see getRedoDescription, redo, canUndo
  13239. */
  13240. bool canRedo() const;
  13241. /** Returns the description of the transaction that would be next to get redone.
  13242. The description returned is the one that was passed into beginNewTransaction
  13243. before the set of actions was performed.
  13244. @see redo
  13245. */
  13246. String getRedoDescription() const;
  13247. /** Tries to redo the last transaction that was undone.
  13248. @returns true if the transaction can be redone, and false if it fails, or
  13249. if there aren't any transactions to redo
  13250. */
  13251. bool redo();
  13252. private:
  13253. OwnedArray <OwnedArray <UndoableAction> > transactions;
  13254. StringArray transactionNames;
  13255. String currentTransactionName;
  13256. int totalUnitsStored, maxNumUnitsToKeep, minimumTransactionsToKeep, nextIndex;
  13257. bool newTransaction, reentrancyCheck;
  13258. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UndoManager);
  13259. };
  13260. #endif // __JUCE_UNDOMANAGER_JUCEHEADER__
  13261. /*** End of inlined file: juce_UndoManager.h ***/
  13262. /**
  13263. A powerful tree structure that can be used to hold free-form data, and which can
  13264. handle its own undo and redo behaviour.
  13265. A ValueTree contains a list of named properties as var objects, and also holds
  13266. any number of sub-trees.
  13267. Create ValueTree objects on the stack, and don't be afraid to copy them around, as
  13268. they're simply a lightweight reference to a shared data container. Creating a copy
  13269. of another ValueTree simply creates a new reference to the same underlying object - to
  13270. make a separate, deep copy of a tree you should explicitly call createCopy().
  13271. Each ValueTree has a type name, in much the same way as an XmlElement has a tag name,
  13272. and much of the structure of a ValueTree is similar to an XmlElement tree.
  13273. You can convert a ValueTree to and from an XmlElement, and as long as the XML doesn't
  13274. contain text elements, the conversion works well and makes a good serialisation
  13275. format. They can also be serialised to a binary format, which is very fast and compact.
  13276. All the methods that change data take an optional UndoManager, which will be used
  13277. to track any changes to the object. For this to work, you have to be careful to
  13278. consistently always use the same UndoManager for all operations to any node inside
  13279. the tree.
  13280. A ValueTree can only be a child of one parent at a time, so if you're moving one from
  13281. one tree to another, be careful to always remove it first, before adding it. This
  13282. could also mess up your undo/redo chain, so be wary! In a debug build you should hit
  13283. assertions if you try to do anything dangerous, but there are still plenty of ways it
  13284. could go wrong.
  13285. Listeners can be added to a ValueTree to be told when properies change and when
  13286. nodes are added or removed.
  13287. @see var, XmlElement
  13288. */
  13289. class JUCE_API ValueTree
  13290. {
  13291. public:
  13292. /** Creates an empty, invalid ValueTree.
  13293. A ValueTree that is created with this constructor can't actually be used for anything,
  13294. it's just a default 'null' ValueTree that can be returned to indicate some sort of failure.
  13295. To create a real one, use the constructor that takes a string.
  13296. @see ValueTree::invalid
  13297. */
  13298. ValueTree() noexcept;
  13299. /** Creates an empty ValueTree with the given type name.
  13300. Like an XmlElement, each ValueTree node has a type, which you can access with
  13301. getType() and hasType().
  13302. */
  13303. explicit ValueTree (const Identifier& type);
  13304. /** Creates a reference to another ValueTree. */
  13305. ValueTree (const ValueTree& other);
  13306. /** Makes this object reference another node. */
  13307. ValueTree& operator= (const ValueTree& other);
  13308. /** Destructor. */
  13309. ~ValueTree();
  13310. /** Returns true if both this and the other tree node refer to the same underlying structure.
  13311. Note that this isn't a value comparison - two independently-created trees which
  13312. contain identical data are not considered equal.
  13313. */
  13314. bool operator== (const ValueTree& other) const noexcept;
  13315. /** Returns true if this and the other node refer to different underlying structures.
  13316. Note that this isn't a value comparison - two independently-created trees which
  13317. contain identical data are not considered equal.
  13318. */
  13319. bool operator!= (const ValueTree& other) const noexcept;
  13320. /** Performs a deep comparison between the properties and children of two trees.
  13321. If all the properties and children of the two trees are the same (recursively), this
  13322. returns true.
  13323. The normal operator==() only checks whether two trees refer to the same shared data
  13324. structure, so use this method if you need to do a proper value comparison.
  13325. */
  13326. bool isEquivalentTo (const ValueTree& other) const;
  13327. /** Returns true if this node refers to some valid data.
  13328. It's hard to create an invalid node, but you might get one returned, e.g. by an out-of-range
  13329. call to getChild().
  13330. */
  13331. bool isValid() const { return object != nullptr; }
  13332. /** Returns a deep copy of this tree and all its sub-nodes. */
  13333. ValueTree createCopy() const;
  13334. /** Returns the type of this node.
  13335. The type is specified when the ValueTree is created.
  13336. @see hasType
  13337. */
  13338. Identifier getType() const;
  13339. /** Returns true if the node has this type.
  13340. The comparison is case-sensitive.
  13341. */
  13342. bool hasType (const Identifier& typeName) const;
  13343. /** Returns the value of a named property.
  13344. If no such property has been set, this will return a void variant.
  13345. You can also use operator[] to get a property.
  13346. @see var, setProperty, hasProperty
  13347. */
  13348. const var& getProperty (const Identifier& name) const;
  13349. /** Returns the value of a named property, or a user-specified default if the property doesn't exist.
  13350. If no such property has been set, this will return the value of defaultReturnValue.
  13351. You can also use operator[] and getProperty to get a property.
  13352. @see var, getProperty, setProperty, hasProperty
  13353. */
  13354. var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  13355. /** Returns the value of a named property.
  13356. If no such property has been set, this will return a void variant. This is the same as
  13357. calling getProperty().
  13358. @see getProperty
  13359. */
  13360. const var& operator[] (const Identifier& name) const;
  13361. /** Changes a named property of the node.
  13362. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13363. so that this change can be undone.
  13364. @see var, getProperty, removeProperty
  13365. */
  13366. void setProperty (const Identifier& name, const var& newValue, UndoManager* undoManager);
  13367. /** Returns true if the node contains a named property. */
  13368. bool hasProperty (const Identifier& name) const;
  13369. /** Removes a property from the node.
  13370. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13371. so that this change can be undone.
  13372. */
  13373. void removeProperty (const Identifier& name, UndoManager* undoManager);
  13374. /** Removes all properties from the node.
  13375. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13376. so that this change can be undone.
  13377. */
  13378. void removeAllProperties (UndoManager* undoManager);
  13379. /** Returns the total number of properties that the node contains.
  13380. @see getProperty.
  13381. */
  13382. int getNumProperties() const;
  13383. /** Returns the identifier of the property with a given index.
  13384. @see getNumProperties
  13385. */
  13386. Identifier getPropertyName (int index) const;
  13387. /** Returns a Value object that can be used to control and respond to one of the tree's properties.
  13388. The Value object will maintain a reference to this tree, and will use the undo manager when
  13389. it needs to change the value. Attaching a Value::Listener to the value object will provide
  13390. callbacks whenever the property changes.
  13391. */
  13392. Value getPropertyAsValue (const Identifier& name, UndoManager* undoManager) const;
  13393. /** Returns the number of child nodes belonging to this one.
  13394. @see getChild
  13395. */
  13396. int getNumChildren() const;
  13397. /** Returns one of this node's child nodes.
  13398. If the index is out of range, it'll return an invalid node. (See isValid() to find out
  13399. whether a node is valid).
  13400. */
  13401. ValueTree getChild (int index) const;
  13402. /** Returns the first child node with the speficied type name.
  13403. If no such node is found, it'll return an invalid node. (See isValid() to find out
  13404. whether a node is valid).
  13405. @see getOrCreateChildWithName
  13406. */
  13407. ValueTree getChildWithName (const Identifier& type) const;
  13408. /** Returns the first child node with the speficied type name, creating and adding
  13409. a child with this name if there wasn't already one there.
  13410. The only time this will return an invalid object is when the object that you're calling
  13411. the method on is itself invalid.
  13412. @see getChildWithName
  13413. */
  13414. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  13415. /** Looks for the first child node that has the speficied property value.
  13416. This will scan the child nodes in order, until it finds one that has property that matches
  13417. the specified value.
  13418. If no such node is found, it'll return an invalid node. (See isValid() to find out
  13419. whether a node is valid).
  13420. */
  13421. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  13422. /** Adds a child to this node.
  13423. Make sure that the child is removed from any former parent node before calling this, or
  13424. you'll hit an assertion.
  13425. If the index is < 0 or greater than the current number of child nodes, the new node will
  13426. be added at the end of the list.
  13427. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13428. so that this change can be undone.
  13429. */
  13430. void addChild (const ValueTree& child, int index, UndoManager* undoManager);
  13431. /** Removes the specified child from this node's child-list.
  13432. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13433. so that this change can be undone.
  13434. */
  13435. void removeChild (const ValueTree& child, UndoManager* undoManager);
  13436. /** Removes a child from this node's child-list.
  13437. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13438. so that this change can be undone.
  13439. */
  13440. void removeChild (int childIndex, UndoManager* undoManager);
  13441. /** Removes all child-nodes from this node.
  13442. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13443. so that this change can be undone.
  13444. */
  13445. void removeAllChildren (UndoManager* undoManager);
  13446. /** Moves one of the children to a different index.
  13447. This will move the child to a specified index, shuffling along any intervening
  13448. items as required. So for example, if you have a list of { 0, 1, 2, 3, 4, 5 }, then
  13449. calling move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  13450. @param currentIndex the index of the item to be moved. If this isn't a
  13451. valid index, then nothing will be done
  13452. @param newIndex the index at which you'd like this item to end up. If this
  13453. is less than zero, the value will be moved to the end
  13454. of the list
  13455. @param undoManager the optional UndoManager to use to store this transaction
  13456. */
  13457. void moveChild (int currentIndex, int newIndex, UndoManager* undoManager);
  13458. /** Returns true if this node is anywhere below the specified parent node.
  13459. This returns true if the node is a child-of-a-child, as well as a direct child.
  13460. */
  13461. bool isAChildOf (const ValueTree& possibleParent) const;
  13462. /** Returns the index of a child item in this parent.
  13463. If the child isn't found, this returns -1.
  13464. */
  13465. int indexOf (const ValueTree& child) const;
  13466. /** Returns the parent node that contains this one.
  13467. If the node has no parent, this will return an invalid node. (See isValid() to find out
  13468. whether a node is valid).
  13469. */
  13470. ValueTree getParent() const;
  13471. /** Returns one of this node's siblings in its parent's child list.
  13472. The delta specifies how far to move through the list, so a value of 1 would return the node
  13473. that follows this one, -1 would return the node before it, 0 will return this node itself, etc.
  13474. If the requested position is beyond the range of available nodes, this will return ValueTree::invalid.
  13475. */
  13476. ValueTree getSibling (int delta) const;
  13477. /** Creates an XmlElement that holds a complete image of this node and all its children.
  13478. If this node is invalid, this may return 0. Otherwise, the XML that is produced can
  13479. be used to recreate a similar node by calling fromXml()
  13480. @see fromXml
  13481. */
  13482. XmlElement* createXml() const;
  13483. /** Tries to recreate a node from its XML representation.
  13484. This isn't designed to cope with random XML data - for a sensible result, it should only
  13485. be fed XML that was created by the createXml() method.
  13486. */
  13487. static ValueTree fromXml (const XmlElement& xml);
  13488. /** Stores this tree (and all its children) in a binary format.
  13489. Once written, the data can be read back with readFromStream().
  13490. It's much faster to load/save your tree in binary form than as XML, but
  13491. obviously isn't human-readable.
  13492. */
  13493. void writeToStream (OutputStream& output);
  13494. /** Reloads a tree from a stream that was written with writeToStream(). */
  13495. static ValueTree readFromStream (InputStream& input);
  13496. /** Reloads a tree from a data block that was written with writeToStream(). */
  13497. static ValueTree readFromData (const void* data, size_t numBytes);
  13498. /** Listener class for events that happen to a ValueTree.
  13499. To get events from a ValueTree, make your class implement this interface, and use
  13500. ValueTree::addListener() and ValueTree::removeListener() to register it.
  13501. */
  13502. class JUCE_API Listener
  13503. {
  13504. public:
  13505. /** Destructor. */
  13506. virtual ~Listener() {}
  13507. /** This method is called when a property of this node (or of one of its sub-nodes) has
  13508. changed.
  13509. The tree parameter indicates which tree has had its property changed, and the property
  13510. parameter indicates the property.
  13511. Note that when you register a listener to a tree, it will receive this callback for
  13512. property changes in that tree, and also for any of its children, (recursively, at any depth).
  13513. If your tree has sub-trees but you only want to know about changes to the top level tree,
  13514. simply check the tree parameter in this callback to make sure it's the tree you're interested in.
  13515. */
  13516. virtual void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged,
  13517. const Identifier& property) = 0;
  13518. /** This method is called when a child sub-tree is added.
  13519. Note that when you register a listener to a tree, it will receive this callback for
  13520. child changes in both that tree and any of its children, (recursively, at any depth).
  13521. If your tree has sub-trees but you only want to know about changes to the top level tree,
  13522. just check the parentTree parameter to make sure it's the one that you're interested in.
  13523. */
  13524. virtual void valueTreeChildAdded (ValueTree& parentTree,
  13525. ValueTree& childWhichHasBeenAdded) = 0;
  13526. /** This method is called when a child sub-tree is removed.
  13527. Note that when you register a listener to a tree, it will receive this callback for
  13528. child changes in both that tree and any of its children, (recursively, at any depth).
  13529. If your tree has sub-trees but you only want to know about changes to the top level tree,
  13530. just check the parentTree parameter to make sure it's the one that you're interested in.
  13531. */
  13532. virtual void valueTreeChildRemoved (ValueTree& parentTree,
  13533. ValueTree& childWhichHasBeenRemoved) = 0;
  13534. /** This method is called when a tree's children have been re-shuffled.
  13535. Note that when you register a listener to a tree, it will receive this callback for
  13536. child changes in both that tree and any of its children, (recursively, at any depth).
  13537. If your tree has sub-trees but you only want to know about changes to the top level tree,
  13538. just check the parameter to make sure it's the tree that you're interested in.
  13539. */
  13540. virtual void valueTreeChildOrderChanged (ValueTree& parentTreeWhoseChildrenHaveMoved) = 0;
  13541. /** This method is called when a tree has been added or removed from a parent node.
  13542. This callback happens when the tree to which the listener was registered is added or
  13543. removed from a parent. Unlike the other callbacks, it applies only to the tree to which
  13544. the listener is registered, and not to any of its children.
  13545. */
  13546. virtual void valueTreeParentChanged (ValueTree& treeWhoseParentHasChanged) = 0;
  13547. };
  13548. /** Adds a listener to receive callbacks when this node is changed.
  13549. The listener is added to this specific ValueTree object, and not to the shared
  13550. object that it refers to. When this object is deleted, all the listeners will
  13551. be lost, even if other references to the same ValueTree still exist. And if you
  13552. use the operator= to make this refer to a different ValueTree, any listeners will
  13553. begin listening to changes to the new tree instead of the old one.
  13554. When you're adding a listener, make sure that you add it to a ValueTree instance that
  13555. will last for as long as you need the listener. In general, you'd never want to add a
  13556. listener to a local stack-based ValueTree, and would usually add one to a member variable.
  13557. @see removeListener
  13558. */
  13559. void addListener (Listener* listener);
  13560. /** Removes a listener that was previously added with addListener(). */
  13561. void removeListener (Listener* listener);
  13562. /** This method uses a comparator object to sort the tree's children into order.
  13563. The object provided must have a method of the form:
  13564. @code
  13565. int compareElements (const ValueTree& first, const ValueTree& second);
  13566. @endcode
  13567. ..and this method must return:
  13568. - a value of < 0 if the first comes before the second
  13569. - a value of 0 if the two objects are equivalent
  13570. - a value of > 0 if the second comes before the first
  13571. To improve performance, the compareElements() method can be declared as static or const.
  13572. @param comparator the comparator to use for comparing elements.
  13573. @param undoManager optional UndoManager for storing the changes
  13574. @param retainOrderOfEquivalentItems if this is true, then items which the comparator says are
  13575. equivalent will be kept in the order in which they currently appear in the array.
  13576. This is slower to perform, but may be important in some cases. If it's false, a
  13577. faster algorithm is used, but equivalent elements may be rearranged.
  13578. */
  13579. template <typename ElementComparator>
  13580. void sort (ElementComparator& comparator, UndoManager* undoManager, bool retainOrderOfEquivalentItems)
  13581. {
  13582. if (object != nullptr)
  13583. {
  13584. ReferenceCountedArray <SharedObject> sortedList (object->children);
  13585. ComparatorAdapter <ElementComparator> adapter (comparator);
  13586. sortedList.sort (adapter, retainOrderOfEquivalentItems);
  13587. object->reorderChildren (sortedList, undoManager);
  13588. }
  13589. }
  13590. /** An invalid ValueTree that can be used if you need to return one as an error condition, etc.
  13591. This invalid object is equivalent to ValueTree created with its default constructor.
  13592. */
  13593. static const ValueTree invalid;
  13594. private:
  13595. class SetPropertyAction; friend class SetPropertyAction;
  13596. class AddOrRemoveChildAction; friend class AddOrRemoveChildAction;
  13597. class MoveChildAction; friend class MoveChildAction;
  13598. class JUCE_API SharedObject : public SingleThreadedReferenceCountedObject
  13599. {
  13600. public:
  13601. explicit SharedObject (const Identifier& type);
  13602. SharedObject (const SharedObject& other);
  13603. ~SharedObject();
  13604. const Identifier type;
  13605. NamedValueSet properties;
  13606. ReferenceCountedArray <SharedObject> children;
  13607. SortedSet <ValueTree*> valueTreesWithListeners;
  13608. SharedObject* parent;
  13609. void sendPropertyChangeMessage (const Identifier& property);
  13610. void sendPropertyChangeMessage (ValueTree& tree, const Identifier& property);
  13611. void sendChildAddedMessage (ValueTree& parent, ValueTree& child);
  13612. void sendChildAddedMessage (ValueTree child);
  13613. void sendChildRemovedMessage (ValueTree& parent, ValueTree& child);
  13614. void sendChildRemovedMessage (ValueTree child);
  13615. void sendChildOrderChangedMessage (ValueTree& parent);
  13616. void sendChildOrderChangedMessage();
  13617. void sendParentChangeMessage();
  13618. const var& getProperty (const Identifier& name) const;
  13619. var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  13620. void setProperty (const Identifier& name, const var& newValue, UndoManager*);
  13621. bool hasProperty (const Identifier& name) const;
  13622. void removeProperty (const Identifier& name, UndoManager*);
  13623. void removeAllProperties (UndoManager*);
  13624. bool isAChildOf (const SharedObject* possibleParent) const;
  13625. int indexOf (const ValueTree& child) const;
  13626. ValueTree getChildWithName (const Identifier& type) const;
  13627. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  13628. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  13629. void addChild (SharedObject* child, int index, UndoManager*);
  13630. void removeChild (int childIndex, UndoManager*);
  13631. void removeAllChildren (UndoManager*);
  13632. void moveChild (int currentIndex, int newIndex, UndoManager*);
  13633. void reorderChildren (const ReferenceCountedArray <SharedObject>& newOrder, UndoManager*);
  13634. bool isEquivalentTo (const SharedObject& other) const;
  13635. XmlElement* createXml() const;
  13636. private:
  13637. SharedObject& operator= (const SharedObject&);
  13638. JUCE_LEAK_DETECTOR (SharedObject);
  13639. };
  13640. template <typename ElementComparator>
  13641. class ComparatorAdapter
  13642. {
  13643. public:
  13644. ComparatorAdapter (ElementComparator& comparator_) noexcept : comparator (comparator_) {}
  13645. int compareElements (SharedObject* const first, SharedObject* const second)
  13646. {
  13647. return comparator.compareElements (ValueTree (first), ValueTree (second));
  13648. }
  13649. private:
  13650. ElementComparator& comparator;
  13651. JUCE_DECLARE_NON_COPYABLE (ComparatorAdapter);
  13652. };
  13653. friend class SharedObject;
  13654. typedef ReferenceCountedObjectPtr <SharedObject> SharedObjectPtr;
  13655. SharedObjectPtr object;
  13656. ListenerList <Listener> listeners;
  13657. #if JUCE_MSVC && ! DOXYGEN
  13658. public: // (workaround for VC6)
  13659. #endif
  13660. explicit ValueTree (SharedObject*);
  13661. };
  13662. #endif // __JUCE_VALUETREE_JUCEHEADER__
  13663. /*** End of inlined file: juce_ValueTree.h ***/
  13664. #endif
  13665. #ifndef __JUCE_VARIANT_JUCEHEADER__
  13666. #endif
  13667. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  13668. /*** Start of inlined file: juce_FileLogger.h ***/
  13669. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  13670. #define __JUCE_FILELOGGER_JUCEHEADER__
  13671. /**
  13672. A simple implemenation of a Logger that writes to a file.
  13673. @see Logger
  13674. */
  13675. class JUCE_API FileLogger : public Logger
  13676. {
  13677. public:
  13678. /** Creates a FileLogger for a given file.
  13679. @param fileToWriteTo the file that to use - new messages will be appended
  13680. to the file. If the file doesn't exist, it will be created,
  13681. along with any parent directories that are needed.
  13682. @param welcomeMessage when opened, the logger will write a header to the log, along
  13683. with the current date and time, and this welcome message
  13684. @param maxInitialFileSizeBytes if this is zero or greater, then if the file already exists
  13685. but is larger than this number of bytes, then the start of the
  13686. file will be truncated to keep the size down. This prevents a log
  13687. file getting ridiculously large over time. The file will be truncated
  13688. at a new-line boundary. If this value is less than zero, no size limit
  13689. will be imposed; if it's zero, the file will always be deleted. Note that
  13690. the size is only checked once when this object is created - any logging
  13691. that is done later will be appended without any checking
  13692. */
  13693. FileLogger (const File& fileToWriteTo,
  13694. const String& welcomeMessage,
  13695. const int maxInitialFileSizeBytes = 128 * 1024);
  13696. /** Destructor. */
  13697. ~FileLogger();
  13698. void logMessage (const String& message);
  13699. File getLogFile() const { return logFile; }
  13700. /** Helper function to create a log file in the correct place for this platform.
  13701. On Windows this will return a logger with a path such as:
  13702. c:\\Documents and Settings\\username\\Application Data\\[logFileSubDirectoryName]\\[logFileName]
  13703. On the Mac it'll create something like:
  13704. ~/Library/Logs/[logFileName]
  13705. The method might return 0 if the file can't be created for some reason.
  13706. @param logFileSubDirectoryName if a subdirectory is needed, this is what it will be called -
  13707. it's best to use the something like the name of your application here.
  13708. @param logFileName the name of the file to create, e.g. "MyAppLog.txt". Don't just
  13709. call it "log.txt" because if it goes in a directory with logs
  13710. from other applications (as it will do on the Mac) then no-one
  13711. will know which one is yours!
  13712. @param welcomeMessage a message that will be written to the log when it's opened.
  13713. @param maxInitialFileSizeBytes (see the FileLogger constructor for more info on this)
  13714. */
  13715. static FileLogger* createDefaultAppLogger (const String& logFileSubDirectoryName,
  13716. const String& logFileName,
  13717. const String& welcomeMessage,
  13718. const int maxInitialFileSizeBytes = 128 * 1024);
  13719. private:
  13720. File logFile;
  13721. CriticalSection logLock;
  13722. void trimFileSize (int maxFileSizeBytes) const;
  13723. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileLogger);
  13724. };
  13725. #endif // __JUCE_FILELOGGER_JUCEHEADER__
  13726. /*** End of inlined file: juce_FileLogger.h ***/
  13727. #endif
  13728. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  13729. /*** Start of inlined file: juce_Initialisation.h ***/
  13730. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  13731. #define __JUCE_INITIALISATION_JUCEHEADER__
  13732. /** Initialises Juce's GUI classes.
  13733. If you're embedding Juce into an application that uses its own event-loop rather
  13734. than using the START_JUCE_APPLICATION macro, call this function before making any
  13735. Juce calls, to make sure things are initialised correctly.
  13736. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  13737. Process::setCurrentModuleInstanceHandle() method.
  13738. @see shutdownJuce_GUI()
  13739. */
  13740. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI();
  13741. /** Clears up any static data being used by Juce's GUI classes.
  13742. If you're embedding Juce into an application that uses its own event-loop rather
  13743. than using the START_JUCE_APPLICATION macro, call this function in your shutdown
  13744. code to clean up any juce objects that might be lying around.
  13745. @see initialiseJuce_GUI()
  13746. */
  13747. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI();
  13748. /** A utility object that helps you initialise and shutdown Juce correctly
  13749. using an RAII pattern.
  13750. When an instance of this class is created, it calls initialiseJuce_GUI(),
  13751. and when it's deleted, it calls shutdownJuce_GUI(), which lets you easily
  13752. make sure that these functions are matched correctly.
  13753. This class is particularly handy to use at the beginning of a console app's
  13754. main() function, because it'll take care of shutting down whenever you return
  13755. from the main() call.
  13756. @see ScopedJuceInitialiser_NonGUI
  13757. */
  13758. class ScopedJuceInitialiser_GUI
  13759. {
  13760. public:
  13761. /** The constructor simply calls initialiseJuce_GUI(). */
  13762. ScopedJuceInitialiser_GUI() { initialiseJuce_GUI(); }
  13763. /** The destructor simply calls shutdownJuce_GUI(). */
  13764. ~ScopedJuceInitialiser_GUI() { shutdownJuce_GUI(); }
  13765. };
  13766. /*
  13767. To start a JUCE app, use this macro: START_JUCE_APPLICATION (AppSubClass) where
  13768. AppSubClass is the name of a class derived from JUCEApplication.
  13769. See the JUCEApplication class documentation (juce_Application.h) for more details.
  13770. */
  13771. #if JUCE_ANDROID
  13772. #define START_JUCE_APPLICATION(AppClass) \
  13773. JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); }
  13774. #elif defined (JUCE_GCC) || defined (__MWERKS__)
  13775. #define START_JUCE_APPLICATION(AppClass) \
  13776. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  13777. int main (int argc, char* argv[]) \
  13778. { \
  13779. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  13780. return JUCE_NAMESPACE::JUCEApplication::main (argc, (const char**) argv); \
  13781. }
  13782. #elif JUCE_WINDOWS
  13783. #ifdef _CONSOLE
  13784. #define START_JUCE_APPLICATION(AppClass) \
  13785. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  13786. int main (int, char* argv[]) \
  13787. { \
  13788. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  13789. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::Process::getCurrentCommandLineParams()); \
  13790. }
  13791. #elif ! defined (_AFXDLL)
  13792. #ifdef _WINDOWS_
  13793. #define START_JUCE_APPLICATION(AppClass) \
  13794. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  13795. int WINAPI WinMain (HINSTANCE, HINSTANCE, LPSTR, int) \
  13796. { \
  13797. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  13798. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::Process::getCurrentCommandLineParams()); \
  13799. }
  13800. #else
  13801. #define START_JUCE_APPLICATION(AppClass) \
  13802. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  13803. int __stdcall WinMain (int, int, const char*, int) \
  13804. { \
  13805. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  13806. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::Process::getCurrentCommandLineParams()); \
  13807. }
  13808. #endif
  13809. #endif
  13810. #endif
  13811. #endif // __JUCE_INITIALISATION_JUCEHEADER__
  13812. /*** End of inlined file: juce_Initialisation.h ***/
  13813. #endif
  13814. #ifndef __JUCE_LOGGER_JUCEHEADER__
  13815. #endif
  13816. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  13817. /*** Start of inlined file: juce_PerformanceCounter.h ***/
  13818. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  13819. #define __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  13820. /** A timer for measuring performance of code and dumping the results to a file.
  13821. e.g. @code
  13822. PerformanceCounter pc ("fish", 50, "/temp/myfishlog.txt");
  13823. for (;;)
  13824. {
  13825. pc.start();
  13826. doSomethingFishy();
  13827. pc.stop();
  13828. }
  13829. @endcode
  13830. In this example, the time of each period between calling start/stop will be
  13831. measured and averaged over 50 runs, and the results printed to a file
  13832. every 50 times round the loop.
  13833. */
  13834. class JUCE_API PerformanceCounter
  13835. {
  13836. public:
  13837. /** Creates a PerformanceCounter object.
  13838. @param counterName the name used when printing out the statistics
  13839. @param runsPerPrintout the number of start/stop iterations before calling
  13840. printStatistics()
  13841. @param loggingFile a file to dump the results to - if this is File::nonexistent,
  13842. the results are just written to the debugger output
  13843. */
  13844. PerformanceCounter (const String& counterName,
  13845. int runsPerPrintout = 100,
  13846. const File& loggingFile = File::nonexistent);
  13847. /** Destructor. */
  13848. ~PerformanceCounter();
  13849. /** Starts timing.
  13850. @see stop
  13851. */
  13852. void start();
  13853. /** Stops timing and prints out the results.
  13854. The number of iterations before doing a printout of the
  13855. results is set in the constructor.
  13856. @see start
  13857. */
  13858. void stop();
  13859. /** Dumps the current metrics to the debugger output and to a file.
  13860. As well as using Logger::outputDebugString to print the results,
  13861. this will write then to the file specified in the constructor (if
  13862. this was valid).
  13863. */
  13864. void printStatistics();
  13865. private:
  13866. String name;
  13867. int numRuns, runsPerPrint;
  13868. double totalTime;
  13869. int64 started;
  13870. File outputFile;
  13871. };
  13872. #endif // __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  13873. /*** End of inlined file: juce_PerformanceCounter.h ***/
  13874. #endif
  13875. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  13876. #endif
  13877. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  13878. #endif
  13879. #ifndef __JUCE_RESULT_JUCEHEADER__
  13880. #endif
  13881. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  13882. /*** Start of inlined file: juce_Singleton.h ***/
  13883. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  13884. #define __JUCE_SINGLETON_JUCEHEADER__
  13885. /**
  13886. Macro to declare member variables and methods for a singleton class.
  13887. To use this, add the line juce_DeclareSingleton (MyClass, doNotRecreateAfterDeletion)
  13888. to the class's definition.
  13889. Then put a macro juce_ImplementSingleton (MyClass) along with the class's
  13890. implementation code.
  13891. It's also a very good idea to also add the call clearSingletonInstance() in your class's
  13892. destructor, in case it is deleted by other means than deleteInstance()
  13893. Clients can then call the static method MyClass::getInstance() to get a pointer
  13894. to the singleton, or MyClass::getInstanceWithoutCreating() which will return 0 if
  13895. no instance currently exists.
  13896. e.g. @code
  13897. class MySingleton
  13898. {
  13899. public:
  13900. MySingleton()
  13901. {
  13902. }
  13903. ~MySingleton()
  13904. {
  13905. // this ensures that no dangling pointers are left when the
  13906. // singleton is deleted.
  13907. clearSingletonInstance();
  13908. }
  13909. juce_DeclareSingleton (MySingleton, false)
  13910. };
  13911. juce_ImplementSingleton (MySingleton)
  13912. // example of usage:
  13913. MySingleton* m = MySingleton::getInstance(); // creates the singleton if there isn't already one.
  13914. ...
  13915. MySingleton::deleteInstance(); // safely deletes the singleton (if it's been created).
  13916. @endcode
  13917. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  13918. than once during the process's lifetime - i.e. after you've created and deleted the
  13919. object, getInstance() will refuse to create another one. This can be useful to stop
  13920. objects being accidentally re-created during your app's shutdown code.
  13921. If you know that your object will only be created and deleted by a single thread, you
  13922. can use the slightly more efficient juce_DeclareSingleton_SingleThreaded() macro instead
  13923. of this one.
  13924. @see juce_ImplementSingleton, juce_DeclareSingleton_SingleThreaded
  13925. */
  13926. #define juce_DeclareSingleton(classname, doNotRecreateAfterDeletion) \
  13927. \
  13928. static classname* _singletonInstance; \
  13929. static JUCE_NAMESPACE::CriticalSection _singletonLock; \
  13930. \
  13931. static classname* JUCE_CALLTYPE getInstance() \
  13932. { \
  13933. if (_singletonInstance == nullptr) \
  13934. {\
  13935. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  13936. \
  13937. if (_singletonInstance == nullptr) \
  13938. { \
  13939. static bool alreadyInside = false; \
  13940. static bool createdOnceAlready = false; \
  13941. \
  13942. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  13943. jassert (! problem); \
  13944. if (! problem) \
  13945. { \
  13946. createdOnceAlready = true; \
  13947. alreadyInside = true; \
  13948. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  13949. alreadyInside = false; \
  13950. \
  13951. _singletonInstance = newObject; \
  13952. } \
  13953. } \
  13954. } \
  13955. \
  13956. return _singletonInstance; \
  13957. } \
  13958. \
  13959. static inline classname* JUCE_CALLTYPE getInstanceWithoutCreating() noexcept\
  13960. { \
  13961. return _singletonInstance; \
  13962. } \
  13963. \
  13964. static void JUCE_CALLTYPE deleteInstance() \
  13965. { \
  13966. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  13967. if (_singletonInstance != nullptr) \
  13968. { \
  13969. classname* const old = _singletonInstance; \
  13970. _singletonInstance = nullptr; \
  13971. delete old; \
  13972. } \
  13973. } \
  13974. \
  13975. void clearSingletonInstance() noexcept\
  13976. { \
  13977. if (_singletonInstance == this) \
  13978. _singletonInstance = nullptr; \
  13979. }
  13980. /** This is a counterpart to the juce_DeclareSingleton macro.
  13981. After adding the juce_DeclareSingleton to the class definition, this macro has
  13982. to be used in the cpp file.
  13983. */
  13984. #define juce_ImplementSingleton(classname) \
  13985. \
  13986. classname* classname::_singletonInstance = nullptr; \
  13987. JUCE_NAMESPACE::CriticalSection classname::_singletonLock;
  13988. /**
  13989. Macro to declare member variables and methods for a singleton class.
  13990. This is exactly the same as juce_DeclareSingleton, but doesn't use a critical
  13991. section to make access to it thread-safe. If you know that your object will
  13992. only ever be created or deleted by a single thread, then this is a
  13993. more efficient version to use.
  13994. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  13995. than once during the process's lifetime - i.e. after you've created and deleted the
  13996. object, getInstance() will refuse to create another one. This can be useful to stop
  13997. objects being accidentally re-created during your app's shutdown code.
  13998. See the documentation for juce_DeclareSingleton for more information about
  13999. how to use it, the only difference being that you have to use
  14000. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  14001. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton, juce_DeclareSingleton_SingleThreaded_Minimal
  14002. */
  14003. #define juce_DeclareSingleton_SingleThreaded(classname, doNotRecreateAfterDeletion) \
  14004. \
  14005. static classname* _singletonInstance; \
  14006. \
  14007. static classname* getInstance() \
  14008. { \
  14009. if (_singletonInstance == nullptr) \
  14010. { \
  14011. static bool alreadyInside = false; \
  14012. static bool createdOnceAlready = false; \
  14013. \
  14014. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  14015. jassert (! problem); \
  14016. if (! problem) \
  14017. { \
  14018. createdOnceAlready = true; \
  14019. alreadyInside = true; \
  14020. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  14021. alreadyInside = false; \
  14022. \
  14023. _singletonInstance = newObject; \
  14024. } \
  14025. } \
  14026. \
  14027. return _singletonInstance; \
  14028. } \
  14029. \
  14030. static inline classname* getInstanceWithoutCreating() noexcept\
  14031. { \
  14032. return _singletonInstance; \
  14033. } \
  14034. \
  14035. static void deleteInstance() \
  14036. { \
  14037. if (_singletonInstance != nullptr) \
  14038. { \
  14039. classname* const old = _singletonInstance; \
  14040. _singletonInstance = nullptr; \
  14041. delete old; \
  14042. } \
  14043. } \
  14044. \
  14045. void clearSingletonInstance() noexcept\
  14046. { \
  14047. if (_singletonInstance == this) \
  14048. _singletonInstance = nullptr; \
  14049. }
  14050. /**
  14051. Macro to declare member variables and methods for a singleton class.
  14052. This is like juce_DeclareSingleton_SingleThreaded, but doesn't do any checking
  14053. for recursion or repeated instantiation. It's intended for use as a lightweight
  14054. version of a singleton, where you're using it in very straightforward
  14055. circumstances and don't need the extra checking.
  14056. Juce use the normal juce_ImplementSingleton_SingleThreaded as the counterpart
  14057. to this declaration, as you would with juce_DeclareSingleton_SingleThreaded.
  14058. See the documentation for juce_DeclareSingleton for more information about
  14059. how to use it, the only difference being that you have to use
  14060. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  14061. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton
  14062. */
  14063. #define juce_DeclareSingleton_SingleThreaded_Minimal(classname) \
  14064. \
  14065. static classname* _singletonInstance; \
  14066. \
  14067. static classname* getInstance() \
  14068. { \
  14069. if (_singletonInstance == nullptr) \
  14070. _singletonInstance = new classname(); \
  14071. \
  14072. return _singletonInstance; \
  14073. } \
  14074. \
  14075. static inline classname* getInstanceWithoutCreating() noexcept\
  14076. { \
  14077. return _singletonInstance; \
  14078. } \
  14079. \
  14080. static void deleteInstance() \
  14081. { \
  14082. if (_singletonInstance != nullptr) \
  14083. { \
  14084. classname* const old = _singletonInstance; \
  14085. _singletonInstance = nullptr; \
  14086. delete old; \
  14087. } \
  14088. } \
  14089. \
  14090. void clearSingletonInstance() noexcept\
  14091. { \
  14092. if (_singletonInstance == this) \
  14093. _singletonInstance = nullptr; \
  14094. }
  14095. /** This is a counterpart to the juce_DeclareSingleton_SingleThreaded macro.
  14096. After adding juce_DeclareSingleton_SingleThreaded or juce_DeclareSingleton_SingleThreaded_Minimal
  14097. to the class definition, this macro has to be used somewhere in the cpp file.
  14098. */
  14099. #define juce_ImplementSingleton_SingleThreaded(classname) \
  14100. \
  14101. classname* classname::_singletonInstance = nullptr;
  14102. #endif // __JUCE_SINGLETON_JUCEHEADER__
  14103. /*** End of inlined file: juce_Singleton.h ***/
  14104. #endif
  14105. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  14106. #endif
  14107. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  14108. /*** Start of inlined file: juce_SystemStats.h ***/
  14109. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  14110. #define __JUCE_SYSTEMSTATS_JUCEHEADER__
  14111. /**
  14112. Contains methods for finding out about the current hardware and OS configuration.
  14113. */
  14114. class JUCE_API SystemStats
  14115. {
  14116. public:
  14117. /** Returns the current version of JUCE,
  14118. See also the JUCE_VERSION, JUCE_MAJOR_VERSION and JUCE_MINOR_VERSION macros.
  14119. */
  14120. static String getJUCEVersion();
  14121. /** The set of possible results of the getOperatingSystemType() method.
  14122. */
  14123. enum OperatingSystemType
  14124. {
  14125. UnknownOS = 0,
  14126. MacOSX = 0x1000,
  14127. Linux = 0x2000,
  14128. Android = 0x3000,
  14129. Win95 = 0x4001,
  14130. Win98 = 0x4002,
  14131. WinNT351 = 0x4103,
  14132. WinNT40 = 0x4104,
  14133. Win2000 = 0x4105,
  14134. WinXP = 0x4106,
  14135. WinVista = 0x4107,
  14136. Windows7 = 0x4108,
  14137. Windows = 0x4000, /**< To test whether any version of Windows is running,
  14138. you can use the expression ((getOperatingSystemType() & Windows) != 0). */
  14139. WindowsNT = 0x0100, /**< To test whether the platform is Windows NT or later (i.e. not Win95 or 98),
  14140. you can use the expression ((getOperatingSystemType() & WindowsNT) != 0). */
  14141. };
  14142. /** Returns the type of operating system we're running on.
  14143. @returns one of the values from the OperatingSystemType enum.
  14144. @see getOperatingSystemName
  14145. */
  14146. static OperatingSystemType getOperatingSystemType();
  14147. /** Returns the name of the type of operating system we're running on.
  14148. @returns a string describing the OS type.
  14149. @see getOperatingSystemType
  14150. */
  14151. static String getOperatingSystemName();
  14152. /** Returns true if the OS is 64-bit, or false for a 32-bit OS.
  14153. */
  14154. static bool isOperatingSystem64Bit();
  14155. #if JUCE_MAC || DOXYGEN
  14156. /** OSX ONLY - Returns the current OS version number.
  14157. E.g. if it's running on 10.4, this will be 4, 10.5 will return 5, etc.
  14158. */
  14159. static int getOSXMinorVersionNumber();
  14160. #endif
  14161. /** Returns the current user's name, if available.
  14162. @see getFullUserName()
  14163. */
  14164. static String getLogonName();
  14165. /** Returns the current user's full name, if available.
  14166. On some OSes, this may just return the same value as getLogonName().
  14167. @see getLogonName()
  14168. */
  14169. static String getFullUserName();
  14170. /** Returns the host-name of the computer. */
  14171. static String getComputerName();
  14172. // CPU and memory information..
  14173. /** Returns the approximate CPU speed.
  14174. @returns the speed in megahertz, e.g. 1500, 2500, 32000 (depending on
  14175. what year you're reading this...)
  14176. */
  14177. static int getCpuSpeedInMegaherz();
  14178. /** Returns a string to indicate the CPU vendor.
  14179. Might not be known on some systems.
  14180. */
  14181. static String getCpuVendor();
  14182. /** Checks whether Intel MMX instructions are available. */
  14183. static bool hasMMX() noexcept { return getCPUFlags().hasMMX; }
  14184. /** Checks whether Intel SSE instructions are available. */
  14185. static bool hasSSE() noexcept { return getCPUFlags().hasSSE; }
  14186. /** Checks whether Intel SSE2 instructions are available. */
  14187. static bool hasSSE2() noexcept { return getCPUFlags().hasSSE2; }
  14188. /** Checks whether AMD 3DNOW instructions are available. */
  14189. static bool has3DNow() noexcept { return getCPUFlags().has3DNow; }
  14190. /** Returns the number of CPUs. */
  14191. static int getNumCpus() noexcept { return getCPUFlags().numCpus; }
  14192. /** Finds out how much RAM is in the machine.
  14193. @returns the approximate number of megabytes of memory, or zero if
  14194. something goes wrong when finding out.
  14195. */
  14196. static int getMemorySizeInMegabytes();
  14197. /** Returns the system page-size.
  14198. This is only used by programmers with beards.
  14199. */
  14200. static int getPageSize();
  14201. private:
  14202. struct CPUFlags
  14203. {
  14204. CPUFlags();
  14205. int numCpus;
  14206. bool hasMMX : 1;
  14207. bool hasSSE : 1;
  14208. bool hasSSE2 : 1;
  14209. bool has3DNow : 1;
  14210. };
  14211. SystemStats();
  14212. static const CPUFlags& getCPUFlags();
  14213. JUCE_DECLARE_NON_COPYABLE (SystemStats);
  14214. };
  14215. #endif // __JUCE_SYSTEMSTATS_JUCEHEADER__
  14216. /*** End of inlined file: juce_SystemStats.h ***/
  14217. #endif
  14218. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  14219. #endif
  14220. #ifndef __JUCE_TIME_JUCEHEADER__
  14221. #endif
  14222. #ifndef __JUCE_UUID_JUCEHEADER__
  14223. /*** Start of inlined file: juce_Uuid.h ***/
  14224. #ifndef __JUCE_UUID_JUCEHEADER__
  14225. #define __JUCE_UUID_JUCEHEADER__
  14226. /**
  14227. A universally unique 128-bit identifier.
  14228. This class generates very random unique numbers based on the system time
  14229. and MAC addresses if any are available. It's extremely unlikely that two identical
  14230. UUIDs would ever be created by chance.
  14231. The class includes methods for saving the ID as a string or as raw binary data.
  14232. */
  14233. class JUCE_API Uuid
  14234. {
  14235. public:
  14236. /** Creates a new unique ID. */
  14237. Uuid();
  14238. /** Destructor. */
  14239. ~Uuid() noexcept;
  14240. /** Creates a copy of another UUID. */
  14241. Uuid (const Uuid& other);
  14242. /** Copies another UUID. */
  14243. Uuid& operator= (const Uuid& other);
  14244. /** Returns true if the ID is zero. */
  14245. bool isNull() const noexcept;
  14246. /** Compares two UUIDs. */
  14247. bool operator== (const Uuid& other) const;
  14248. /** Compares two UUIDs. */
  14249. bool operator!= (const Uuid& other) const;
  14250. /** Returns a stringified version of this UUID.
  14251. A Uuid object can later be reconstructed from this string using operator= or
  14252. the constructor that takes a string parameter.
  14253. @returns a 32 character hex string.
  14254. */
  14255. String toString() const;
  14256. /** Creates an ID from an encoded string version.
  14257. @see toString
  14258. */
  14259. Uuid (const String& uuidString);
  14260. /** Copies from a stringified UUID.
  14261. The string passed in should be one that was created with the toString() method.
  14262. */
  14263. Uuid& operator= (const String& uuidString);
  14264. /** Returns a pointer to the internal binary representation of the ID.
  14265. This is an array of 16 bytes. To reconstruct a Uuid from its data, use
  14266. the constructor or operator= method that takes an array of uint8s.
  14267. */
  14268. const uint8* getRawData() const noexcept { return value.asBytes; }
  14269. /** Creates a UUID from a 16-byte array.
  14270. @see getRawData
  14271. */
  14272. Uuid (const uint8* rawData);
  14273. /** Sets this UUID from 16-bytes of raw data. */
  14274. Uuid& operator= (const uint8* rawData);
  14275. private:
  14276. #ifndef DOXYGEN
  14277. union
  14278. {
  14279. uint8 asBytes [16];
  14280. int asInt[4];
  14281. int64 asInt64[2];
  14282. } value;
  14283. #endif
  14284. JUCE_LEAK_DETECTOR (Uuid);
  14285. };
  14286. #endif // __JUCE_UUID_JUCEHEADER__
  14287. /*** End of inlined file: juce_Uuid.h ***/
  14288. #endif
  14289. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  14290. /*** Start of inlined file: juce_BlowFish.h ***/
  14291. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  14292. #define __JUCE_BLOWFISH_JUCEHEADER__
  14293. /**
  14294. BlowFish encryption class.
  14295. */
  14296. class JUCE_API BlowFish
  14297. {
  14298. public:
  14299. /** Creates an object that can encode/decode based on the specified key.
  14300. The key data can be up to 72 bytes long.
  14301. */
  14302. BlowFish (const void* keyData, int keyBytes);
  14303. /** Creates a copy of another blowfish object. */
  14304. BlowFish (const BlowFish& other);
  14305. /** Copies another blowfish object. */
  14306. BlowFish& operator= (const BlowFish& other);
  14307. /** Destructor. */
  14308. ~BlowFish();
  14309. /** Encrypts a pair of 32-bit integers. */
  14310. void encrypt (uint32& data1, uint32& data2) const noexcept;
  14311. /** Decrypts a pair of 32-bit integers. */
  14312. void decrypt (uint32& data1, uint32& data2) const noexcept;
  14313. private:
  14314. uint32 p[18];
  14315. HeapBlock <uint32> s[4];
  14316. uint32 F (uint32 x) const noexcept;
  14317. JUCE_LEAK_DETECTOR (BlowFish);
  14318. };
  14319. #endif // __JUCE_BLOWFISH_JUCEHEADER__
  14320. /*** End of inlined file: juce_BlowFish.h ***/
  14321. #endif
  14322. #ifndef __JUCE_MD5_JUCEHEADER__
  14323. /*** Start of inlined file: juce_MD5.h ***/
  14324. #ifndef __JUCE_MD5_JUCEHEADER__
  14325. #define __JUCE_MD5_JUCEHEADER__
  14326. /**
  14327. MD5 checksum class.
  14328. Create one of these with a block of source data or a string, and it calculates the
  14329. MD5 checksum of that data.
  14330. You can then retrieve this checksum as a 16-byte block, or as a hex string.
  14331. */
  14332. class JUCE_API MD5
  14333. {
  14334. public:
  14335. /** Creates a null MD5 object. */
  14336. MD5();
  14337. /** Creates a copy of another MD5. */
  14338. MD5 (const MD5& other);
  14339. /** Copies another MD5. */
  14340. MD5& operator= (const MD5& other);
  14341. /** Creates a checksum for a block of binary data. */
  14342. explicit MD5 (const MemoryBlock& data);
  14343. /** Creates a checksum for a block of binary data. */
  14344. MD5 (const void* data, size_t numBytes);
  14345. /** Creates a checksum for a string.
  14346. Note that this operates on the string as a block of unicode characters, so the
  14347. result you get will differ from the value you'd get if the string was treated
  14348. as a block of utf8 or ascii. Bear this in mind if you're comparing the result
  14349. of this method with a checksum created by a different framework, which may have
  14350. used a different encoding.
  14351. */
  14352. explicit MD5 (const String& text);
  14353. /** Creates a checksum for the input from a stream.
  14354. This will read up to the given number of bytes from the stream, and produce the
  14355. checksum of that. If the number of bytes to read is negative, it'll read
  14356. until the stream is exhausted.
  14357. */
  14358. MD5 (InputStream& input, int64 numBytesToRead = -1);
  14359. /** Creates a checksum for a file. */
  14360. explicit MD5 (const File& file);
  14361. /** Destructor. */
  14362. ~MD5();
  14363. /** Returns the checksum as a 16-byte block of data. */
  14364. MemoryBlock getRawChecksumData() const;
  14365. /** Returns the checksum as a 32-digit hex string. */
  14366. String toHexString() const;
  14367. /** Compares this to another MD5. */
  14368. bool operator== (const MD5& other) const;
  14369. /** Compares this to another MD5. */
  14370. bool operator!= (const MD5& other) const;
  14371. private:
  14372. uint8 result [16];
  14373. struct ProcessContext
  14374. {
  14375. uint8 buffer [64];
  14376. uint32 state [4];
  14377. uint32 count [2];
  14378. ProcessContext();
  14379. void processBlock (const void* data, size_t dataSize);
  14380. void transform (const void* buffer);
  14381. void finish (void* result);
  14382. };
  14383. void processStream (InputStream&, int64 numBytesToRead);
  14384. JUCE_LEAK_DETECTOR (MD5);
  14385. };
  14386. #endif // __JUCE_MD5_JUCEHEADER__
  14387. /*** End of inlined file: juce_MD5.h ***/
  14388. #endif
  14389. #ifndef __JUCE_PRIMES_JUCEHEADER__
  14390. /*** Start of inlined file: juce_Primes.h ***/
  14391. #ifndef __JUCE_PRIMES_JUCEHEADER__
  14392. #define __JUCE_PRIMES_JUCEHEADER__
  14393. /*** Start of inlined file: juce_BigInteger.h ***/
  14394. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  14395. #define __JUCE_BIGINTEGER_JUCEHEADER__
  14396. class MemoryBlock;
  14397. /**
  14398. An arbitrarily large integer class.
  14399. A BigInteger can be used in a similar way to a normal integer, but has no size
  14400. limit (except for memory and performance constraints).
  14401. Negative values are possible, but the value isn't stored as 2s-complement, so
  14402. be careful if you use negative values and look at the values of individual bits.
  14403. */
  14404. class JUCE_API BigInteger
  14405. {
  14406. public:
  14407. /** Creates an empty BigInteger */
  14408. BigInteger();
  14409. /** Creates a BigInteger containing an integer value in its low bits.
  14410. The low 32 bits of the number are initialised with this value.
  14411. */
  14412. BigInteger (uint32 value);
  14413. /** Creates a BigInteger containing an integer value in its low bits.
  14414. The low 32 bits of the number are initialised with the absolute value
  14415. passed in, and its sign is set to reflect the sign of the number.
  14416. */
  14417. BigInteger (int32 value);
  14418. /** Creates a BigInteger containing an integer value in its low bits.
  14419. The low 64 bits of the number are initialised with the absolute value
  14420. passed in, and its sign is set to reflect the sign of the number.
  14421. */
  14422. BigInteger (int64 value);
  14423. /** Creates a copy of another BigInteger. */
  14424. BigInteger (const BigInteger& other);
  14425. /** Destructor. */
  14426. ~BigInteger();
  14427. /** Copies another BigInteger onto this one. */
  14428. BigInteger& operator= (const BigInteger& other);
  14429. /** Swaps the internal contents of this with another object. */
  14430. void swapWith (BigInteger& other) noexcept;
  14431. /** Returns the value of a specified bit in the number.
  14432. If the index is out-of-range, the result will be false.
  14433. */
  14434. bool operator[] (int bit) const noexcept;
  14435. /** Returns true if no bits are set. */
  14436. bool isZero() const noexcept;
  14437. /** Returns true if the value is 1. */
  14438. bool isOne() const noexcept;
  14439. /** Attempts to get the lowest bits of the value as an integer.
  14440. If the value is bigger than the integer limits, this will return only the lower bits.
  14441. */
  14442. int toInteger() const noexcept;
  14443. /** Resets the value to 0. */
  14444. void clear();
  14445. /** Clears a particular bit in the number. */
  14446. void clearBit (int bitNumber) noexcept;
  14447. /** Sets a specified bit to 1. */
  14448. void setBit (int bitNumber);
  14449. /** Sets or clears a specified bit. */
  14450. void setBit (int bitNumber, bool shouldBeSet);
  14451. /** Sets a range of bits to be either on or off.
  14452. @param startBit the first bit to change
  14453. @param numBits the number of bits to change
  14454. @param shouldBeSet whether to turn these bits on or off
  14455. */
  14456. void setRange (int startBit, int numBits, bool shouldBeSet);
  14457. /** Inserts a bit an a given position, shifting up any bits above it. */
  14458. void insertBit (int bitNumber, bool shouldBeSet);
  14459. /** Returns a range of bits as a new BigInteger.
  14460. e.g. getBitRangeAsInt (0, 64) would return the lowest 64 bits.
  14461. @see getBitRangeAsInt
  14462. */
  14463. BigInteger getBitRange (int startBit, int numBits) const;
  14464. /** Returns a range of bits as an integer value.
  14465. e.g. getBitRangeAsInt (0, 32) would return the lowest 32 bits.
  14466. Asking for more than 32 bits isn't allowed (obviously) - for that, use
  14467. getBitRange().
  14468. */
  14469. int getBitRangeAsInt (int startBit, int numBits) const noexcept;
  14470. /** Sets a range of bits to an integer value.
  14471. Copies the given integer onto a range of bits, starting at startBit,
  14472. and using up to numBits of the available bits.
  14473. */
  14474. void setBitRangeAsInt (int startBit, int numBits, uint32 valueToSet);
  14475. /** Shifts a section of bits left or right.
  14476. @param howManyBitsLeft how far to move the bits (+ve numbers shift it left, -ve numbers shift it right).
  14477. @param startBit the first bit to affect - if this is > 0, only bits above that index will be affected.
  14478. */
  14479. void shiftBits (int howManyBitsLeft, int startBit);
  14480. /** Returns the total number of set bits in the value. */
  14481. int countNumberOfSetBits() const noexcept;
  14482. /** Looks for the index of the next set bit after a given starting point.
  14483. This searches from startIndex (inclusive) upwards for the first set bit,
  14484. and returns its index. If no set bits are found, it returns -1.
  14485. */
  14486. int findNextSetBit (int startIndex = 0) const noexcept;
  14487. /** Looks for the index of the next clear bit after a given starting point.
  14488. This searches from startIndex (inclusive) upwards for the first clear bit,
  14489. and returns its index.
  14490. */
  14491. int findNextClearBit (int startIndex = 0) const noexcept;
  14492. /** Returns the index of the highest set bit in the number.
  14493. If the value is zero, this will return -1.
  14494. */
  14495. int getHighestBit() const noexcept;
  14496. // All the standard arithmetic ops...
  14497. BigInteger& operator+= (const BigInteger& other);
  14498. BigInteger& operator-= (const BigInteger& other);
  14499. BigInteger& operator*= (const BigInteger& other);
  14500. BigInteger& operator/= (const BigInteger& other);
  14501. BigInteger& operator|= (const BigInteger& other);
  14502. BigInteger& operator&= (const BigInteger& other);
  14503. BigInteger& operator^= (const BigInteger& other);
  14504. BigInteger& operator%= (const BigInteger& other);
  14505. BigInteger& operator<<= (int numBitsToShift);
  14506. BigInteger& operator>>= (int numBitsToShift);
  14507. BigInteger& operator++();
  14508. BigInteger& operator--();
  14509. BigInteger operator++ (int);
  14510. BigInteger operator-- (int);
  14511. BigInteger operator-() const;
  14512. BigInteger operator+ (const BigInteger& other) const;
  14513. BigInteger operator- (const BigInteger& other) const;
  14514. BigInteger operator* (const BigInteger& other) const;
  14515. BigInteger operator/ (const BigInteger& other) const;
  14516. BigInteger operator| (const BigInteger& other) const;
  14517. BigInteger operator& (const BigInteger& other) const;
  14518. BigInteger operator^ (const BigInteger& other) const;
  14519. BigInteger operator% (const BigInteger& other) const;
  14520. BigInteger operator<< (int numBitsToShift) const;
  14521. BigInteger operator>> (int numBitsToShift) const;
  14522. bool operator== (const BigInteger& other) const noexcept;
  14523. bool operator!= (const BigInteger& other) const noexcept;
  14524. bool operator< (const BigInteger& other) const noexcept;
  14525. bool operator<= (const BigInteger& other) const noexcept;
  14526. bool operator> (const BigInteger& other) const noexcept;
  14527. bool operator>= (const BigInteger& other) const noexcept;
  14528. /** Does a signed comparison of two BigIntegers.
  14529. Return values are:
  14530. - 0 if the numbers are the same
  14531. - < 0 if this number is smaller than the other
  14532. - > 0 if this number is bigger than the other
  14533. */
  14534. int compare (const BigInteger& other) const noexcept;
  14535. /** Compares the magnitudes of two BigIntegers, ignoring their signs.
  14536. Return values are:
  14537. - 0 if the numbers are the same
  14538. - < 0 if this number is smaller than the other
  14539. - > 0 if this number is bigger than the other
  14540. */
  14541. int compareAbsolute (const BigInteger& other) const noexcept;
  14542. /** Divides this value by another one and returns the remainder.
  14543. This number is divided by other, leaving the quotient in this number,
  14544. with the remainder being copied to the other BigInteger passed in.
  14545. */
  14546. void divideBy (const BigInteger& divisor, BigInteger& remainder);
  14547. /** Returns the largest value that will divide both this value and the one passed-in.
  14548. */
  14549. BigInteger findGreatestCommonDivisor (BigInteger other) const;
  14550. /** Performs a combined exponent and modulo operation.
  14551. This BigInteger's value becomes (this ^ exponent) % modulus.
  14552. */
  14553. void exponentModulo (const BigInteger& exponent, const BigInteger& modulus);
  14554. /** Performs an inverse modulo on the value.
  14555. i.e. the result is (this ^ -1) mod (modulus).
  14556. */
  14557. void inverseModulo (const BigInteger& modulus);
  14558. /** Returns true if the value is less than zero.
  14559. @see setNegative, negate
  14560. */
  14561. bool isNegative() const noexcept;
  14562. /** Changes the sign of the number to be positive or negative.
  14563. @see isNegative, negate
  14564. */
  14565. void setNegative (bool shouldBeNegative) noexcept;
  14566. /** Inverts the sign of the number.
  14567. @see isNegative, setNegative
  14568. */
  14569. void negate() noexcept;
  14570. /** Converts the number to a string.
  14571. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  14572. If minimumNumCharacters is greater than 0, the returned string will be
  14573. padded with leading zeros to reach at least that length.
  14574. */
  14575. String toString (int base, int minimumNumCharacters = 1) const;
  14576. /** Reads the numeric value from a string.
  14577. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  14578. Any invalid characters will be ignored.
  14579. */
  14580. void parseString (const String& text, int base);
  14581. /** Turns the number into a block of binary data.
  14582. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  14583. of the number, and so on.
  14584. @see loadFromMemoryBlock
  14585. */
  14586. MemoryBlock toMemoryBlock() const;
  14587. /** Converts a block of raw data into a number.
  14588. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  14589. of the number, and so on.
  14590. @see toMemoryBlock
  14591. */
  14592. void loadFromMemoryBlock (const MemoryBlock& data);
  14593. private:
  14594. HeapBlock <uint32> values;
  14595. int numValues, highestBit;
  14596. bool negative;
  14597. void ensureSize (int numVals);
  14598. void shiftLeft (int bits, int startBit);
  14599. void shiftRight (int bits, int startBit);
  14600. static BigInteger simpleGCD (BigInteger* m, BigInteger* n);
  14601. static inline int bitToIndex (const int bit) noexcept { return bit >> 5; }
  14602. static inline uint32 bitToMask (const int bit) noexcept { return 1 << (bit & 31); }
  14603. JUCE_LEAK_DETECTOR (BigInteger);
  14604. };
  14605. /** Writes a BigInteger to an OutputStream as a UTF8 decimal string. */
  14606. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value);
  14607. #ifndef DOXYGEN
  14608. // For backwards compatibility, BitArray is defined as an alias for BigInteger.
  14609. typedef BigInteger BitArray;
  14610. #endif
  14611. #endif // __JUCE_BIGINTEGER_JUCEHEADER__
  14612. /*** End of inlined file: juce_BigInteger.h ***/
  14613. /**
  14614. Prime number creation class.
  14615. This class contains static methods for generating and testing prime numbers.
  14616. @see BigInteger
  14617. */
  14618. class JUCE_API Primes
  14619. {
  14620. public:
  14621. /** Creates a random prime number with a given bit-length.
  14622. The certainty parameter specifies how many iterations to use when testing
  14623. for primality. A safe value might be anything over about 20-30.
  14624. The randomSeeds parameter lets you optionally pass it a set of values with
  14625. which to seed the random number generation, improving the security of the
  14626. keys generated.
  14627. */
  14628. static BigInteger createProbablePrime (int bitLength,
  14629. int certainty,
  14630. const int* randomSeeds = 0,
  14631. int numRandomSeeds = 0);
  14632. /** Tests a number to see if it's prime.
  14633. This isn't a bulletproof test, it uses a Miller-Rabin test to determine
  14634. whether the number is prime.
  14635. The certainty parameter specifies how many iterations to use when testing - a
  14636. safe value might be anything over about 20-30.
  14637. */
  14638. static bool isProbablyPrime (const BigInteger& number, int certainty);
  14639. private:
  14640. Primes();
  14641. JUCE_DECLARE_NON_COPYABLE (Primes);
  14642. };
  14643. #endif // __JUCE_PRIMES_JUCEHEADER__
  14644. /*** End of inlined file: juce_Primes.h ***/
  14645. #endif
  14646. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  14647. /*** Start of inlined file: juce_RSAKey.h ***/
  14648. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  14649. #define __JUCE_RSAKEY_JUCEHEADER__
  14650. /**
  14651. RSA public/private key-pair encryption class.
  14652. An object of this type makes up one half of a public/private RSA key pair. Use the
  14653. createKeyPair() method to create a matching pair for encoding/decoding.
  14654. */
  14655. class JUCE_API RSAKey
  14656. {
  14657. public:
  14658. /** Creates a null key object.
  14659. Initialise a pair of objects for use with the createKeyPair() method.
  14660. */
  14661. RSAKey();
  14662. /** Loads a key from an encoded string representation.
  14663. This reloads a key from a string created by the toString() method.
  14664. */
  14665. explicit RSAKey (const String& stringRepresentation);
  14666. /** Destructor. */
  14667. ~RSAKey();
  14668. bool operator== (const RSAKey& other) const noexcept;
  14669. bool operator!= (const RSAKey& other) const noexcept;
  14670. /** Turns the key into a string representation.
  14671. This can be reloaded using the constructor that takes a string.
  14672. */
  14673. String toString() const;
  14674. /** Encodes or decodes a value.
  14675. Call this on the public key object to encode some data, then use the matching
  14676. private key object to decode it.
  14677. Returns false if the operation couldn't be completed, e.g. if this key hasn't been
  14678. initialised correctly.
  14679. NOTE: This method dumbly applies this key to this data. If you encode some data
  14680. and then try to decode it with a key that doesn't match, this method will still
  14681. happily do its job and return true, but the result won't be what you were expecting.
  14682. It's your responsibility to check that the result is what you wanted.
  14683. */
  14684. bool applyToValue (BigInteger& value) const;
  14685. /** Creates a public/private key-pair.
  14686. Each key will perform one-way encryption that can only be reversed by
  14687. using the other key.
  14688. The numBits parameter specifies the size of key, e.g. 128, 256, 512 bit. Bigger
  14689. sizes are more secure, but this method will take longer to execute.
  14690. The randomSeeds parameter lets you optionally pass it a set of values with
  14691. which to seed the random number generation, improving the security of the
  14692. keys generated. If you supply these, make sure you provide more than 2 values,
  14693. and the more your provide, the better the security.
  14694. */
  14695. static void createKeyPair (RSAKey& publicKey,
  14696. RSAKey& privateKey,
  14697. int numBits,
  14698. const int* randomSeeds = nullptr,
  14699. int numRandomSeeds = 0);
  14700. protected:
  14701. BigInteger part1, part2;
  14702. private:
  14703. static BigInteger findBestCommonDivisor (const BigInteger& p, const BigInteger& q);
  14704. JUCE_LEAK_DETECTOR (RSAKey);
  14705. };
  14706. #endif // __JUCE_RSAKEY_JUCEHEADER__
  14707. /*** End of inlined file: juce_RSAKey.h ***/
  14708. #endif
  14709. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14710. /*** Start of inlined file: juce_DirectoryIterator.h ***/
  14711. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14712. #define __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14713. /**
  14714. Searches through a the files in a directory, returning each file that is found.
  14715. A DirectoryIterator will search through a directory and its subdirectories using
  14716. a wildcard filepattern match.
  14717. If you may be finding a large number of files, this is better than
  14718. using File::findChildFiles() because it doesn't block while it finds them
  14719. all, and this is more memory-efficient.
  14720. It can also guess how far it's got using a wildly inaccurate algorithm.
  14721. */
  14722. class JUCE_API DirectoryIterator
  14723. {
  14724. public:
  14725. /** Creates a DirectoryIterator for a given directory.
  14726. After creating one of these, call its next() method to get the
  14727. first file - e.g. @code
  14728. DirectoryIterator iter (File ("/animals/mooses"), true, "*.moose");
  14729. while (iter.next())
  14730. {
  14731. File theFileItFound (iter.getFile());
  14732. ... etc
  14733. }
  14734. @endcode
  14735. @param directory the directory to search in
  14736. @param isRecursive whether all the subdirectories should also be searched
  14737. @param wildCard the file pattern to match
  14738. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying
  14739. whether to look for files, directories, or both.
  14740. */
  14741. DirectoryIterator (const File& directory,
  14742. bool isRecursive,
  14743. const String& wildCard = "*",
  14744. int whatToLookFor = File::findFiles);
  14745. /** Destructor. */
  14746. ~DirectoryIterator();
  14747. /** Moves the iterator along to the next file.
  14748. @returns true if a file was found (you can then use getFile() to see what it was) - or
  14749. false if there are no more matching files.
  14750. */
  14751. bool next();
  14752. /** Moves the iterator along to the next file, and returns various properties of that file.
  14753. If you need to find out details about the file, it's more efficient to call this method than
  14754. to call the normal next() method and then find out the details afterwards.
  14755. All the parameters are optional, so pass null pointers for any items that you're not
  14756. interested in.
  14757. @returns true if a file was found (you can then use getFile() to see what it was) - or
  14758. false if there are no more matching files. If it returns false, then none of the
  14759. parameters will be filled-in.
  14760. */
  14761. bool next (bool* isDirectory,
  14762. bool* isHidden,
  14763. int64* fileSize,
  14764. Time* modTime,
  14765. Time* creationTime,
  14766. bool* isReadOnly);
  14767. /** Returns the file that the iterator is currently pointing at.
  14768. The result of this call is only valid after a call to next() has returned true.
  14769. */
  14770. const File& getFile() const;
  14771. /** Returns a guess of how far through the search the iterator has got.
  14772. @returns a value 0.0 to 1.0 to show the progress, although this won't be
  14773. very accurate.
  14774. */
  14775. float getEstimatedProgress() const;
  14776. private:
  14777. class NativeIterator
  14778. {
  14779. public:
  14780. NativeIterator (const File& directory, const String& wildCard);
  14781. ~NativeIterator();
  14782. bool next (String& filenameFound,
  14783. bool* isDirectory, bool* isHidden, int64* fileSize,
  14784. Time* modTime, Time* creationTime, bool* isReadOnly);
  14785. class Pimpl;
  14786. private:
  14787. friend class DirectoryIterator;
  14788. friend class ScopedPointer<Pimpl>;
  14789. ScopedPointer<Pimpl> pimpl;
  14790. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeIterator);
  14791. };
  14792. friend class ScopedPointer<NativeIterator::Pimpl>;
  14793. NativeIterator fileFinder;
  14794. String wildCard, path;
  14795. int index;
  14796. mutable int totalNumFiles;
  14797. const int whatToLookFor;
  14798. const bool isRecursive;
  14799. bool hasBeenAdvanced;
  14800. ScopedPointer <DirectoryIterator> subIterator;
  14801. File currentFile;
  14802. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectoryIterator);
  14803. };
  14804. #endif // __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14805. /*** End of inlined file: juce_DirectoryIterator.h ***/
  14806. #endif
  14807. #ifndef __JUCE_FILE_JUCEHEADER__
  14808. #endif
  14809. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14810. /*** Start of inlined file: juce_FileInputStream.h ***/
  14811. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14812. #define __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14813. /**
  14814. An input stream that reads from a local file.
  14815. @see InputStream, FileOutputStream, File::createInputStream
  14816. */
  14817. class JUCE_API FileInputStream : public InputStream
  14818. {
  14819. public:
  14820. /** Creates a FileInputStream.
  14821. @param fileToRead the file to read from - if the file can't be accessed for some
  14822. reason, then the stream will just contain no data
  14823. */
  14824. explicit FileInputStream (const File& fileToRead);
  14825. /** Destructor. */
  14826. ~FileInputStream();
  14827. /** Returns the file that this stream is reading from. */
  14828. const File& getFile() const noexcept { return file; }
  14829. /** Returns the status of the file stream.
  14830. The result will be ok if the file opened successfully. If an error occurs while
  14831. opening or reading from the file, this will contain an error message.
  14832. */
  14833. Result getStatus() const { return status; }
  14834. int64 getTotalLength();
  14835. int read (void* destBuffer, int maxBytesToRead);
  14836. bool isExhausted();
  14837. int64 getPosition();
  14838. bool setPosition (int64 pos);
  14839. private:
  14840. File file;
  14841. void* fileHandle;
  14842. int64 currentPosition, totalSize;
  14843. Result status;
  14844. bool needToSeek;
  14845. void openHandle();
  14846. void closeHandle();
  14847. size_t readInternal (void* buffer, size_t numBytes);
  14848. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileInputStream);
  14849. };
  14850. #endif // __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14851. /*** End of inlined file: juce_FileInputStream.h ***/
  14852. #endif
  14853. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  14854. /*** Start of inlined file: juce_FileOutputStream.h ***/
  14855. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  14856. #define __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  14857. /**
  14858. An output stream that writes into a local file.
  14859. @see OutputStream, FileInputStream, File::createOutputStream
  14860. */
  14861. class JUCE_API FileOutputStream : public OutputStream
  14862. {
  14863. public:
  14864. /** Creates a FileOutputStream.
  14865. If the file doesn't exist, it will first be created. If the file can't be
  14866. created or opened, the failedToOpen() method will return
  14867. true.
  14868. If the file already exists when opened, the stream's write-postion will
  14869. be set to the end of the file. To overwrite an existing file,
  14870. use File::deleteFile() before opening the stream, or use setPosition(0)
  14871. after it's opened (although this won't truncate the file).
  14872. It's better to use File::createOutputStream() to create one of these, rather
  14873. than using the class directly.
  14874. @see TemporaryFile
  14875. */
  14876. FileOutputStream (const File& fileToWriteTo,
  14877. int bufferSizeToUse = 16384);
  14878. /** Destructor. */
  14879. ~FileOutputStream();
  14880. /** Returns the file that this stream is writing to.
  14881. */
  14882. const File& getFile() const { return file; }
  14883. /** Returns the status of the file stream.
  14884. The result will be ok if the file opened successfully. If an error occurs while
  14885. opening or writing to the file, this will contain an error message.
  14886. */
  14887. Result getStatus() const { return status; }
  14888. /** Returns true if the stream couldn't be opened for some reason.
  14889. @see getResult()
  14890. */
  14891. bool failedToOpen() const { return status.failed(); }
  14892. void flush();
  14893. int64 getPosition();
  14894. bool setPosition (int64 pos);
  14895. bool write (const void* data, int numBytes);
  14896. void writeRepeatedByte (uint8 byte, int numTimesToRepeat);
  14897. private:
  14898. File file;
  14899. void* fileHandle;
  14900. Result status;
  14901. int64 currentPosition;
  14902. int bufferSize, bytesInBuffer;
  14903. HeapBlock <char> buffer;
  14904. void openHandle();
  14905. void closeHandle();
  14906. void flushInternal();
  14907. bool flushBuffer();
  14908. int64 setPositionInternal (int64 newPosition);
  14909. int writeInternal (const void* data, int numBytes);
  14910. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileOutputStream);
  14911. };
  14912. #endif // __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  14913. /*** End of inlined file: juce_FileOutputStream.h ***/
  14914. #endif
  14915. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  14916. /*** Start of inlined file: juce_FileSearchPath.h ***/
  14917. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  14918. #define __JUCE_FILESEARCHPATH_JUCEHEADER__
  14919. /**
  14920. Encapsulates a set of folders that make up a search path.
  14921. @see File
  14922. */
  14923. class JUCE_API FileSearchPath
  14924. {
  14925. public:
  14926. /** Creates an empty search path. */
  14927. FileSearchPath();
  14928. /** Creates a search path from a string of pathnames.
  14929. The path can be semicolon- or comma-separated, e.g.
  14930. "/foo/bar;/foo/moose;/fish/moose"
  14931. The separate folders are tokenised and added to the search path.
  14932. */
  14933. FileSearchPath (const String& path);
  14934. /** Creates a copy of another search path. */
  14935. FileSearchPath (const FileSearchPath& other);
  14936. /** Destructor. */
  14937. ~FileSearchPath();
  14938. /** Uses a string containing a list of pathnames to re-initialise this list.
  14939. This search path is cleared and the semicolon- or comma-separated folders
  14940. in this string are added instead. e.g. "/foo/bar;/foo/moose;/fish/moose"
  14941. */
  14942. FileSearchPath& operator= (const String& path);
  14943. /** Returns the number of folders in this search path.
  14944. @see operator[]
  14945. */
  14946. int getNumPaths() const;
  14947. /** Returns one of the folders in this search path.
  14948. The file returned isn't guaranteed to actually be a valid directory.
  14949. @see getNumPaths
  14950. */
  14951. File operator[] (int index) const;
  14952. /** Returns the search path as a semicolon-separated list of directories. */
  14953. String toString() const;
  14954. /** Adds a new directory to the search path.
  14955. The new directory is added to the end of the list if the insertIndex parameter is
  14956. less than zero, otherwise it is inserted at the given index.
  14957. */
  14958. void add (const File& directoryToAdd,
  14959. int insertIndex = -1);
  14960. /** Adds a new directory to the search path if it's not already in there. */
  14961. void addIfNotAlreadyThere (const File& directoryToAdd);
  14962. /** Removes a directory from the search path. */
  14963. void remove (int indexToRemove);
  14964. /** Merges another search path into this one.
  14965. This will remove any duplicate directories.
  14966. */
  14967. void addPath (const FileSearchPath& other);
  14968. /** Removes any directories that are actually subdirectories of one of the other directories in the search path.
  14969. If the search is intended to be recursive, there's no point having nested folders in the search
  14970. path, because they'll just get searched twice and you'll get duplicate results.
  14971. e.g. if the path is "c:\abc\de;c:\abc", this method will simplify it to "c:\abc"
  14972. */
  14973. void removeRedundantPaths();
  14974. /** Removes any directories that don't actually exist. */
  14975. void removeNonExistentPaths();
  14976. /** Searches the path for a wildcard.
  14977. This will search all the directories in the search path in order, adding any
  14978. matching files to the results array.
  14979. @param results an array to append the results to
  14980. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying whether to
  14981. return files, directories, or both.
  14982. @param searchRecursively whether to recursively search the subdirectories too
  14983. @param wildCardPattern a pattern to match against the filenames
  14984. @returns the number of files added to the array
  14985. @see File::findChildFiles
  14986. */
  14987. int findChildFiles (Array<File>& results,
  14988. int whatToLookFor,
  14989. bool searchRecursively,
  14990. const String& wildCardPattern = "*") const;
  14991. /** Finds out whether a file is inside one of the path's directories.
  14992. This will return true if the specified file is a child of one of the
  14993. directories specified by this path. Note that this doesn't actually do any
  14994. searching or check that the files exist - it just looks at the pathnames
  14995. to work out whether the file would be inside a directory.
  14996. @param fileToCheck the file to look for
  14997. @param checkRecursively if true, then this will return true if the file is inside a
  14998. subfolder of one of the path's directories (at any depth). If false
  14999. it will only return true if the file is actually a direct child
  15000. of one of the directories.
  15001. @see File::isAChildOf
  15002. */
  15003. bool isFileInPath (const File& fileToCheck,
  15004. bool checkRecursively) const;
  15005. private:
  15006. StringArray directories;
  15007. void init (const String& path);
  15008. JUCE_LEAK_DETECTOR (FileSearchPath);
  15009. };
  15010. #endif // __JUCE_FILESEARCHPATH_JUCEHEADER__
  15011. /*** End of inlined file: juce_FileSearchPath.h ***/
  15012. #endif
  15013. #ifndef __JUCE_MEMORYMAPPEDFILE_JUCEHEADER__
  15014. /*** Start of inlined file: juce_MemoryMappedFile.h ***/
  15015. #ifndef __JUCE_MEMORYMAPPEDFILE_JUCEHEADER__
  15016. #define __JUCE_MEMORYMAPPEDFILE_JUCEHEADER__
  15017. /**
  15018. Maps a file into virtual memory for easy reading and/or writing.
  15019. */
  15020. class JUCE_API MemoryMappedFile
  15021. {
  15022. public:
  15023. /** The read/write flags used when opening a memory mapped file. */
  15024. enum AccessMode
  15025. {
  15026. readOnly, /**< Indicates that the memory can only be read. */
  15027. readWrite /**< Indicates that the memory can be read and written to - changes that are
  15028. made will be flushed back to disk at the whim of the OS. */
  15029. };
  15030. /** Opens a file and maps it to an area of virtual memory.
  15031. The file should already exist, and should already be the size that you want to work with
  15032. when you call this. If the file is resized after being opened, the behaviour is undefined.
  15033. If the file exists and the operation succeeds, the getData() and getSize() methods will
  15034. return the location and size of the data that can be read or written. Note that the entire
  15035. file is not read into memory immediately - the OS simply creates a virtual mapping, which
  15036. will lazily pull the data into memory when blocks are accessed.
  15037. If the file can't be opened for some reason, the getData() method will return a null pointer.
  15038. */
  15039. MemoryMappedFile (const File& file, AccessMode mode);
  15040. /** Destructor. */
  15041. ~MemoryMappedFile();
  15042. /** Returns the address at which this file has been mapped, or a null pointer if
  15043. the file couldn't be successfully mapped.
  15044. */
  15045. void* getData() const noexcept { return address; }
  15046. /** Returns the number of bytes of data that are available for reading or writing.
  15047. This will normally be the size of the file.
  15048. */
  15049. size_t getSize() const noexcept { return length; }
  15050. private:
  15051. void* address;
  15052. size_t length;
  15053. #if JUCE_WINDOWS
  15054. void* fileHandle;
  15055. #else
  15056. int fileHandle;
  15057. #endif
  15058. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MemoryMappedFile);
  15059. };
  15060. #endif // __JUCE_MEMORYMAPPEDFILE_JUCEHEADER__
  15061. /*** End of inlined file: juce_MemoryMappedFile.h ***/
  15062. #endif
  15063. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  15064. /*** Start of inlined file: juce_NamedPipe.h ***/
  15065. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  15066. #define __JUCE_NAMEDPIPE_JUCEHEADER__
  15067. /**
  15068. A cross-process pipe that can have data written to and read from it.
  15069. Two or more processes can use these for inter-process communication.
  15070. @see InterprocessConnection
  15071. */
  15072. class JUCE_API NamedPipe
  15073. {
  15074. public:
  15075. /** Creates a NamedPipe. */
  15076. NamedPipe();
  15077. /** Destructor. */
  15078. ~NamedPipe();
  15079. /** Tries to open a pipe that already exists.
  15080. Returns true if it succeeds.
  15081. */
  15082. bool openExisting (const String& pipeName);
  15083. /** Tries to create a new pipe.
  15084. Returns true if it succeeds.
  15085. */
  15086. bool createNewPipe (const String& pipeName);
  15087. /** Closes the pipe, if it's open. */
  15088. void close();
  15089. /** True if the pipe is currently open. */
  15090. bool isOpen() const;
  15091. /** Returns the last name that was used to try to open this pipe. */
  15092. String getName() const;
  15093. /** Reads data from the pipe.
  15094. This will block until another thread has written enough data into the pipe to fill
  15095. the number of bytes specified, or until another thread calls the cancelPendingReads()
  15096. method.
  15097. If the operation fails, it returns -1, otherwise, it will return the number of
  15098. bytes read.
  15099. If timeOutMilliseconds is less than zero, it will wait indefinitely, otherwise
  15100. this is a maximum timeout for reading from the pipe.
  15101. */
  15102. int read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds = 5000);
  15103. /** Writes some data to the pipe.
  15104. If the operation fails, it returns -1, otherwise, it will return the number of
  15105. bytes written.
  15106. */
  15107. int write (const void* sourceBuffer, int numBytesToWrite,
  15108. int timeOutMilliseconds = 2000);
  15109. /** If any threads are currently blocked on a read operation, this tells them to abort.
  15110. */
  15111. void cancelPendingReads();
  15112. private:
  15113. void* internal;
  15114. String currentPipeName;
  15115. CriticalSection lock;
  15116. bool openInternal (const String& pipeName, const bool createPipe);
  15117. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NamedPipe);
  15118. };
  15119. #endif // __JUCE_NAMEDPIPE_JUCEHEADER__
  15120. /*** End of inlined file: juce_NamedPipe.h ***/
  15121. #endif
  15122. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  15123. /*** Start of inlined file: juce_TemporaryFile.h ***/
  15124. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  15125. #define __JUCE_TEMPORARYFILE_JUCEHEADER__
  15126. /**
  15127. Manages a temporary file, which will be deleted when this object is deleted.
  15128. This object is intended to be used as a stack based object, using its scope
  15129. to make sure the temporary file isn't left lying around.
  15130. For example:
  15131. @code
  15132. {
  15133. File myTargetFile ("~/myfile.txt");
  15134. // this will choose a file called something like "~/myfile_temp239348.txt"
  15135. // which definitely doesn't exist at the time the constructor is called.
  15136. TemporaryFile temp (myTargetFile);
  15137. // create a stream to the temporary file, and write some data to it...
  15138. ScopedPointer <FileOutputStream> out (temp.getFile().createOutputStream());
  15139. if (out != nullptr)
  15140. {
  15141. out->write ( ...etc )
  15142. out->flush();
  15143. out = nullptr; // (deletes the stream)
  15144. // ..now we've finished writing, this will rename the temp file to
  15145. // make it replace the target file we specified above.
  15146. bool succeeded = temp.overwriteTargetFileWithTemporary();
  15147. }
  15148. // ..and even if something went wrong and our overwrite failed,
  15149. // as the TemporaryFile object goes out of scope here, it'll make sure
  15150. // that the temp file gets deleted.
  15151. }
  15152. @endcode
  15153. @see File, FileOutputStream
  15154. */
  15155. class JUCE_API TemporaryFile
  15156. {
  15157. public:
  15158. enum OptionFlags
  15159. {
  15160. useHiddenFile = 1, /**< Indicates that the temporary file should be hidden -
  15161. i.e. its name should start with a dot. */
  15162. putNumbersInBrackets = 2 /**< Indicates that when numbers are appended to make sure
  15163. the file is unique, they should go in brackets rather
  15164. than just being appended (see File::getNonexistentSibling() )*/
  15165. };
  15166. /** Creates a randomly-named temporary file in the default temp directory.
  15167. @param suffix a file suffix to use for the file
  15168. @param optionFlags a combination of the values listed in the OptionFlags enum
  15169. The file will not be created until you write to it. And remember that when
  15170. this object is deleted, the file will also be deleted!
  15171. */
  15172. TemporaryFile (const String& suffix = String::empty,
  15173. int optionFlags = 0);
  15174. /** Creates a temporary file in the same directory as a specified file.
  15175. This is useful if you have a file that you want to overwrite, but don't
  15176. want to harm the original file if the write operation fails. You can
  15177. use this to create a temporary file next to the target file, then
  15178. write to the temporary file, and finally use overwriteTargetFileWithTemporary()
  15179. to replace the target file with the one you've just written.
  15180. This class won't create any files until you actually write to them. And remember
  15181. that when this object is deleted, the temporary file will also be deleted!
  15182. @param targetFile the file that you intend to overwrite - the temporary
  15183. file will be created in the same directory as this
  15184. @param optionFlags a combination of the values listed in the OptionFlags enum
  15185. */
  15186. TemporaryFile (const File& targetFile,
  15187. int optionFlags = 0);
  15188. /** Destructor.
  15189. When this object is deleted it will make sure that its temporary file is
  15190. also deleted! If the operation fails, it'll throw an assertion in debug
  15191. mode.
  15192. */
  15193. ~TemporaryFile();
  15194. /** Returns the temporary file. */
  15195. const File& getFile() const { return temporaryFile; }
  15196. /** Returns the target file that was specified in the constructor. */
  15197. const File& getTargetFile() const { return targetFile; }
  15198. /** Tries to move the temporary file to overwrite the target file that was
  15199. specified in the constructor.
  15200. If you used the constructor that specified a target file, this will attempt
  15201. to replace that file with the temporary one.
  15202. Before calling this, make sure:
  15203. - that you've actually written to the temporary file
  15204. - that you've closed any open streams that you were using to write to it
  15205. - and that you don't have any streams open to the target file, which would
  15206. prevent it being overwritten
  15207. If the file move succeeds, this returns false, and the temporary file will
  15208. have disappeared. If it fails, the temporary file will probably still exist,
  15209. but will be deleted when this object is destroyed.
  15210. */
  15211. bool overwriteTargetFileWithTemporary() const;
  15212. /** Attempts to delete the temporary file, if it exists.
  15213. @returns true if the file is successfully deleted (or if it didn't exist).
  15214. */
  15215. bool deleteTemporaryFile() const;
  15216. private:
  15217. File temporaryFile, targetFile;
  15218. void createTempFile (const File& parentDirectory, String name, const String& suffix, int optionFlags);
  15219. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TemporaryFile);
  15220. };
  15221. #endif // __JUCE_TEMPORARYFILE_JUCEHEADER__
  15222. /*** End of inlined file: juce_TemporaryFile.h ***/
  15223. #endif
  15224. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  15225. /*** Start of inlined file: juce_ZipFile.h ***/
  15226. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  15227. #define __JUCE_ZIPFILE_JUCEHEADER__
  15228. /*** Start of inlined file: juce_InputSource.h ***/
  15229. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  15230. #define __JUCE_INPUTSOURCE_JUCEHEADER__
  15231. /**
  15232. A lightweight object that can create a stream to read some kind of resource.
  15233. This may be used to refer to a file, or some other kind of source, allowing a
  15234. caller to create an input stream that can read from it when required.
  15235. @see FileInputSource
  15236. */
  15237. class JUCE_API InputSource
  15238. {
  15239. public:
  15240. InputSource() noexcept {}
  15241. /** Destructor. */
  15242. virtual ~InputSource() {}
  15243. /** Returns a new InputStream to read this item.
  15244. @returns an inputstream that the caller will delete, or 0 if
  15245. the filename isn't found.
  15246. */
  15247. virtual InputStream* createInputStream() = 0;
  15248. /** Returns a new InputStream to read an item, relative.
  15249. @param relatedItemPath the relative pathname of the resource that is required
  15250. @returns an inputstream that the caller will delete, or 0 if
  15251. the item isn't found.
  15252. */
  15253. virtual InputStream* createInputStreamFor (const String& relatedItemPath) = 0;
  15254. /** Returns a hash code that uniquely represents this item.
  15255. */
  15256. virtual int64 hashCode() const = 0;
  15257. private:
  15258. JUCE_LEAK_DETECTOR (InputSource);
  15259. };
  15260. #endif // __JUCE_INPUTSOURCE_JUCEHEADER__
  15261. /*** End of inlined file: juce_InputSource.h ***/
  15262. /**
  15263. Decodes a ZIP file from a stream.
  15264. This can enumerate the items in a ZIP file and can create suitable stream objects
  15265. to read each one.
  15266. */
  15267. class JUCE_API ZipFile
  15268. {
  15269. public:
  15270. /** Creates a ZipFile for a given stream.
  15271. @param inputStream the stream to read from
  15272. @param deleteStreamWhenDestroyed if set to true, the object passed-in
  15273. will be deleted when this ZipFile object is deleted
  15274. */
  15275. ZipFile (InputStream* inputStream, bool deleteStreamWhenDestroyed);
  15276. /** Creates a ZipFile based for a file. */
  15277. ZipFile (const File& file);
  15278. /** Creates a ZipFile for an input source.
  15279. The inputSource object will be owned by the zip file, which will delete
  15280. it later when not needed.
  15281. */
  15282. ZipFile (InputSource* inputSource);
  15283. /** Destructor. */
  15284. ~ZipFile();
  15285. /**
  15286. Contains information about one of the entries in a ZipFile.
  15287. @see ZipFile::getEntry
  15288. */
  15289. struct ZipEntry
  15290. {
  15291. /** The name of the file, which may also include a partial pathname. */
  15292. String filename;
  15293. /** The file's original size. */
  15294. unsigned int uncompressedSize;
  15295. /** The last time the file was modified. */
  15296. Time fileTime;
  15297. };
  15298. /** Returns the number of items in the zip file. */
  15299. int getNumEntries() const noexcept;
  15300. /** Returns a structure that describes one of the entries in the zip file.
  15301. This may return zero if the index is out of range.
  15302. @see ZipFile::ZipEntry
  15303. */
  15304. const ZipEntry* getEntry (int index) const noexcept;
  15305. /** Returns the index of the first entry with a given filename.
  15306. This uses a case-sensitive comparison to look for a filename in the
  15307. list of entries. It might return -1 if no match is found.
  15308. @see ZipFile::ZipEntry
  15309. */
  15310. int getIndexOfFileName (const String& fileName) const noexcept;
  15311. /** Returns a structure that describes one of the entries in the zip file.
  15312. This uses a case-sensitive comparison to look for a filename in the
  15313. list of entries. It might return 0 if no match is found.
  15314. @see ZipFile::ZipEntry
  15315. */
  15316. const ZipEntry* getEntry (const String& fileName) const noexcept;
  15317. /** Sorts the list of entries, based on the filename.
  15318. */
  15319. void sortEntriesByFilename();
  15320. /** Creates a stream that can read from one of the zip file's entries.
  15321. The stream that is returned must be deleted by the caller (and
  15322. zero might be returned if a stream can't be opened for some reason).
  15323. The stream must not be used after the ZipFile object that created
  15324. has been deleted.
  15325. */
  15326. InputStream* createStreamForEntry (int index);
  15327. /** Creates a stream that can read from one of the zip file's entries.
  15328. The stream that is returned must be deleted by the caller (and
  15329. zero might be returned if a stream can't be opened for some reason).
  15330. The stream must not be used after the ZipFile object that created
  15331. has been deleted.
  15332. */
  15333. InputStream* createStreamForEntry (ZipEntry& entry);
  15334. /** Uncompresses all of the files in the zip file.
  15335. This will expand all the entries into a target directory. The relative
  15336. paths of the entries are used.
  15337. @param targetDirectory the root folder to uncompress to
  15338. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  15339. @returns true if all the files are successfully unzipped
  15340. */
  15341. bool uncompressTo (const File& targetDirectory,
  15342. bool shouldOverwriteFiles = true);
  15343. /** Uncompresses one of the entries from the zip file.
  15344. This will expand the entry and write it in a target directory. The entry's path is used to
  15345. determine which subfolder of the target should contain the new file.
  15346. @param index the index of the entry to uncompress
  15347. @param targetDirectory the root folder to uncompress into
  15348. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  15349. @returns true if the files is successfully unzipped
  15350. */
  15351. bool uncompressEntry (int index,
  15352. const File& targetDirectory,
  15353. bool shouldOverwriteFiles = true);
  15354. /** Used to create a new zip file.
  15355. Create a ZipFile::Builder object, and call its addFile() method to add some files,
  15356. then you can write it to a stream with write().
  15357. Currently this just stores the files with no compression.. That will be added
  15358. soon!
  15359. */
  15360. class Builder
  15361. {
  15362. public:
  15363. Builder();
  15364. ~Builder();
  15365. /** Adds a file while should be added to the archive.
  15366. The file isn't read immediately, all the files will be read later when the writeToStream()
  15367. method is called.
  15368. The compressionLevel can be between 0 (no compression), and 9 (maximum compression).
  15369. If the storedPathName parameter is specified, you can customise the partial pathname that
  15370. will be stored for this file.
  15371. */
  15372. void addFile (const File& fileToAdd, int compressionLevel,
  15373. const String& storedPathName = String::empty);
  15374. /** Generates the zip file, writing it to the specified stream. */
  15375. bool writeToStream (OutputStream& target) const;
  15376. private:
  15377. class Item;
  15378. friend class OwnedArray<Item>;
  15379. OwnedArray<Item> items;
  15380. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Builder);
  15381. };
  15382. private:
  15383. class ZipInputStream;
  15384. class ZipFilenameComparator;
  15385. class ZipEntryInfo;
  15386. friend class ZipInputStream;
  15387. friend class ZipFilenameComparator;
  15388. friend class ZipEntryInfo;
  15389. OwnedArray <ZipEntryInfo> entries;
  15390. CriticalSection lock;
  15391. InputStream* inputStream;
  15392. ScopedPointer <InputStream> streamToDelete;
  15393. ScopedPointer <InputSource> inputSource;
  15394. #if JUCE_DEBUG
  15395. int numOpenStreams;
  15396. #endif
  15397. void init();
  15398. int findEndOfZipEntryTable (InputStream& input, int& numEntries);
  15399. static int compareElements (const ZipEntryInfo* first, const ZipEntryInfo* second);
  15400. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ZipFile);
  15401. };
  15402. #endif // __JUCE_ZIPFILE_JUCEHEADER__
  15403. /*** End of inlined file: juce_ZipFile.h ***/
  15404. #endif
  15405. #ifndef __JUCE_MACADDRESS_JUCEHEADER__
  15406. /*** Start of inlined file: juce_MACAddress.h ***/
  15407. #ifndef __JUCE_MACADDRESS_JUCEHEADER__
  15408. #define __JUCE_MACADDRESS_JUCEHEADER__
  15409. /**
  15410. A wrapper for a streaming (TCP) socket.
  15411. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  15412. sockets, you could also try the InterprocessConnection class.
  15413. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  15414. */
  15415. class JUCE_API MACAddress
  15416. {
  15417. public:
  15418. /** Populates a list of the MAC addresses of all the available network cards. */
  15419. static void findAllAddresses (Array<MACAddress>& results);
  15420. /** Creates a null address (00-00-00-00-00-00). */
  15421. MACAddress();
  15422. /** Creates a copy of another address. */
  15423. MACAddress (const MACAddress& other);
  15424. /** Creates a copy of another address. */
  15425. MACAddress& operator= (const MACAddress& other);
  15426. /** Creates an address from 6 bytes. */
  15427. explicit MACAddress (const uint8 bytes[6]);
  15428. /** Returns a pointer to the 6 bytes that make up this address. */
  15429. const uint8* getBytes() const noexcept { return asBytes; }
  15430. /** Returns a dash-separated string in the form "11-22-33-44-55-66" */
  15431. String toString() const;
  15432. /** Returns the address in the lower 6 bytes of an int64.
  15433. This uses a little-endian arrangement, with the first byte of the address being
  15434. stored in the least-significant byte of the result value.
  15435. */
  15436. int64 toInt64() const noexcept;
  15437. /** Returns true if this address is null (00-00-00-00-00-00). */
  15438. bool isNull() const noexcept;
  15439. bool operator== (const MACAddress& other) const noexcept;
  15440. bool operator!= (const MACAddress& other) const noexcept;
  15441. private:
  15442. #ifndef DOXYGEN
  15443. union
  15444. {
  15445. uint64 asInt64;
  15446. uint8 asBytes[6];
  15447. };
  15448. #endif
  15449. };
  15450. #endif // __JUCE_MACADDRESS_JUCEHEADER__
  15451. /*** End of inlined file: juce_MACAddress.h ***/
  15452. #endif
  15453. #ifndef __JUCE_SOCKET_JUCEHEADER__
  15454. /*** Start of inlined file: juce_Socket.h ***/
  15455. #ifndef __JUCE_SOCKET_JUCEHEADER__
  15456. #define __JUCE_SOCKET_JUCEHEADER__
  15457. /**
  15458. A wrapper for a streaming (TCP) socket.
  15459. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  15460. sockets, you could also try the InterprocessConnection class.
  15461. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  15462. */
  15463. class JUCE_API StreamingSocket
  15464. {
  15465. public:
  15466. /** Creates an uninitialised socket.
  15467. To connect it, use the connect() method, after which you can read() or write()
  15468. to it.
  15469. To wait for other sockets to connect to this one, the createListener() method
  15470. enters "listener" mode, and can be used to spawn new sockets for each connection
  15471. that comes along.
  15472. */
  15473. StreamingSocket();
  15474. /** Destructor. */
  15475. ~StreamingSocket();
  15476. /** Binds the socket to the specified local port.
  15477. @returns true on success; false may indicate that another socket is already bound
  15478. on the same port
  15479. */
  15480. bool bindToPort (int localPortNumber);
  15481. /** Tries to connect the socket to hostname:port.
  15482. If timeOutMillisecs is 0, then this method will block until the operating system
  15483. rejects the connection (which could take a long time).
  15484. @returns true if it succeeds.
  15485. @see isConnected
  15486. */
  15487. bool connect (const String& remoteHostname,
  15488. int remotePortNumber,
  15489. int timeOutMillisecs = 3000);
  15490. /** True if the socket is currently connected. */
  15491. bool isConnected() const noexcept { return connected; }
  15492. /** Closes the connection. */
  15493. void close();
  15494. /** Returns the name of the currently connected host. */
  15495. const String& getHostName() const noexcept { return hostName; }
  15496. /** Returns the port number that's currently open. */
  15497. int getPort() const noexcept { return portNumber; }
  15498. /** True if the socket is connected to this machine rather than over the network. */
  15499. bool isLocal() const noexcept;
  15500. /** Waits until the socket is ready for reading or writing.
  15501. If readyForReading is true, it will wait until the socket is ready for
  15502. reading; if false, it will wait until it's ready for writing.
  15503. If the timeout is < 0, it will wait forever, or else will give up after
  15504. the specified time.
  15505. If the socket is ready on return, this returns 1. If it times-out before
  15506. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  15507. */
  15508. int waitUntilReady (bool readyForReading,
  15509. int timeoutMsecs) const;
  15510. /** Reads bytes from the socket.
  15511. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  15512. maxBytesToRead bytes have been read, (or until an error occurs). If this
  15513. flag is false, the method will return as much data as is currently available
  15514. without blocking.
  15515. @returns the number of bytes read, or -1 if there was an error.
  15516. @see waitUntilReady
  15517. */
  15518. int read (void* destBuffer, int maxBytesToRead,
  15519. bool blockUntilSpecifiedAmountHasArrived);
  15520. /** Writes bytes to the socket from a buffer.
  15521. Note that this method will block unless you have checked the socket is ready
  15522. for writing before calling it (see the waitUntilReady() method).
  15523. @returns the number of bytes written, or -1 if there was an error.
  15524. */
  15525. int write (const void* sourceBuffer, int numBytesToWrite);
  15526. /** Puts this socket into "listener" mode.
  15527. When in this mode, your thread can call waitForNextConnection() repeatedly,
  15528. which will spawn new sockets for each new connection, so that these can
  15529. be handled in parallel by other threads.
  15530. @param portNumber the port number to listen on
  15531. @param localHostName the interface address to listen on - pass an empty
  15532. string to listen on all addresses
  15533. @returns true if it manages to open the socket successfully.
  15534. @see waitForNextConnection
  15535. */
  15536. bool createListener (int portNumber, const String& localHostName = String::empty);
  15537. /** When in "listener" mode, this waits for a connection and spawns it as a new
  15538. socket.
  15539. The object that gets returned will be owned by the caller.
  15540. This method can only be called after using createListener().
  15541. @see createListener
  15542. */
  15543. StreamingSocket* waitForNextConnection() const;
  15544. private:
  15545. String hostName;
  15546. int volatile portNumber, handle;
  15547. bool connected, isListener;
  15548. StreamingSocket (const String& hostname, int portNumber, int handle);
  15549. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StreamingSocket);
  15550. };
  15551. /**
  15552. A wrapper for a datagram (UDP) socket.
  15553. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  15554. sockets, you could also try the InterprocessConnection class.
  15555. @see StreamingSocket, InterprocessConnection, InterprocessConnectionServer
  15556. */
  15557. class JUCE_API DatagramSocket
  15558. {
  15559. public:
  15560. /**
  15561. Creates an (uninitialised) datagram socket.
  15562. The localPortNumber is the port on which to bind this socket. If this value is 0,
  15563. the port number is assigned by the operating system.
  15564. To use the socket for sending, call the connect() method. This will not immediately
  15565. make a connection, but will save the destination you've provided. After this, you can
  15566. call read() or write().
  15567. If enableBroadcasting is true, the socket will be allowed to send broadcast messages
  15568. (may require extra privileges on linux)
  15569. To wait for other sockets to connect to this one, call waitForNextConnection().
  15570. */
  15571. DatagramSocket (int localPortNumber,
  15572. bool enableBroadcasting = false);
  15573. /** Destructor. */
  15574. ~DatagramSocket();
  15575. /** Binds the socket to the specified local port.
  15576. @returns true on success; false may indicate that another socket is already bound
  15577. on the same port
  15578. */
  15579. bool bindToPort (int localPortNumber);
  15580. /** Tries to connect the socket to hostname:port.
  15581. If timeOutMillisecs is 0, then this method will block until the operating system
  15582. rejects the connection (which could take a long time).
  15583. @returns true if it succeeds.
  15584. @see isConnected
  15585. */
  15586. bool connect (const String& remoteHostname,
  15587. int remotePortNumber,
  15588. int timeOutMillisecs = 3000);
  15589. /** True if the socket is currently connected. */
  15590. bool isConnected() const noexcept { return connected; }
  15591. /** Closes the connection. */
  15592. void close();
  15593. /** Returns the name of the currently connected host. */
  15594. const String& getHostName() const noexcept { return hostName; }
  15595. /** Returns the port number that's currently open. */
  15596. int getPort() const noexcept { return portNumber; }
  15597. /** True if the socket is connected to this machine rather than over the network. */
  15598. bool isLocal() const noexcept;
  15599. /** Waits until the socket is ready for reading or writing.
  15600. If readyForReading is true, it will wait until the socket is ready for
  15601. reading; if false, it will wait until it's ready for writing.
  15602. If the timeout is < 0, it will wait forever, or else will give up after
  15603. the specified time.
  15604. If the socket is ready on return, this returns 1. If it times-out before
  15605. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  15606. */
  15607. int waitUntilReady (bool readyForReading,
  15608. int timeoutMsecs) const;
  15609. /** Reads bytes from the socket.
  15610. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  15611. maxBytesToRead bytes have been read, (or until an error occurs). If this
  15612. flag is false, the method will return as much data as is currently available
  15613. without blocking.
  15614. @returns the number of bytes read, or -1 if there was an error.
  15615. @see waitUntilReady
  15616. */
  15617. int read (void* destBuffer, int maxBytesToRead,
  15618. bool blockUntilSpecifiedAmountHasArrived);
  15619. /** Writes bytes to the socket from a buffer.
  15620. Note that this method will block unless you have checked the socket is ready
  15621. for writing before calling it (see the waitUntilReady() method).
  15622. @returns the number of bytes written, or -1 if there was an error.
  15623. */
  15624. int write (const void* sourceBuffer, int numBytesToWrite);
  15625. /** This waits for incoming data to be sent, and returns a socket that can be used
  15626. to read it.
  15627. The object that gets returned is owned by the caller, and can't be used for
  15628. sending, but can be used to read the data.
  15629. */
  15630. DatagramSocket* waitForNextConnection() const;
  15631. private:
  15632. String hostName;
  15633. int volatile portNumber, handle;
  15634. bool connected, allowBroadcast;
  15635. void* serverAddress;
  15636. DatagramSocket (const String& hostname, int portNumber, int handle, int localPortNumber);
  15637. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DatagramSocket);
  15638. };
  15639. #endif // __JUCE_SOCKET_JUCEHEADER__
  15640. /*** End of inlined file: juce_Socket.h ***/
  15641. #endif
  15642. #ifndef __JUCE_URL_JUCEHEADER__
  15643. /*** Start of inlined file: juce_URL.h ***/
  15644. #ifndef __JUCE_URL_JUCEHEADER__
  15645. #define __JUCE_URL_JUCEHEADER__
  15646. class InputStream;
  15647. class XmlElement;
  15648. /**
  15649. Represents a URL and has a bunch of useful functions to manipulate it.
  15650. This class can be used to launch URLs in browsers, and also to create
  15651. InputStreams that can read from remote http or ftp sources.
  15652. */
  15653. class JUCE_API URL
  15654. {
  15655. public:
  15656. /** Creates an empty URL. */
  15657. URL();
  15658. /** Creates a URL from a string. */
  15659. URL (const String& url);
  15660. /** Creates a copy of another URL. */
  15661. URL (const URL& other);
  15662. /** Destructor. */
  15663. ~URL();
  15664. /** Copies this URL from another one. */
  15665. URL& operator= (const URL& other);
  15666. /** Returns a string version of the URL.
  15667. If includeGetParameters is true and any parameters have been set with the
  15668. withParameter() method, then the string will have these appended on the
  15669. end and url-encoded.
  15670. */
  15671. String toString (bool includeGetParameters) const;
  15672. /** True if it seems to be valid. */
  15673. bool isWellFormed() const;
  15674. /** Returns just the domain part of the URL.
  15675. E.g. for "http://www.xyz.com/foobar", this will return "www.xyz.com".
  15676. */
  15677. String getDomain() const;
  15678. /** Returns the path part of the URL.
  15679. E.g. for "http://www.xyz.com/foo/bar?x=1", this will return "foo/bar".
  15680. */
  15681. String getSubPath() const;
  15682. /** Returns the scheme of the URL.
  15683. E.g. for "http://www.xyz.com/foobar", this will return "http". (It won't
  15684. include the colon).
  15685. */
  15686. String getScheme() const;
  15687. /** Returns a new version of this URL that uses a different sub-path.
  15688. E.g. if the URL is "http://www.xyz.com/foo?x=1" and you call this with
  15689. "bar", it'll return "http://www.xyz.com/bar?x=1".
  15690. */
  15691. const URL withNewSubPath (const String& newPath) const;
  15692. /** Returns a copy of this URL, with a GET or POST parameter added to the end.
  15693. Any control characters in the value will be encoded.
  15694. e.g. calling "withParameter ("amount", "some fish") for the url "www.fish.com"
  15695. would produce a new url whose toString(true) method would return
  15696. "www.fish.com?amount=some+fish".
  15697. */
  15698. const URL withParameter (const String& parameterName,
  15699. const String& parameterValue) const;
  15700. /** Returns a copy of this URl, with a file-upload type parameter added to it.
  15701. When performing a POST where one of your parameters is a binary file, this
  15702. lets you specify the file.
  15703. Note that the filename is stored, but the file itself won't actually be read
  15704. until this URL is later used to create a network input stream.
  15705. */
  15706. const URL withFileToUpload (const String& parameterName,
  15707. const File& fileToUpload,
  15708. const String& mimeType) const;
  15709. /** Returns a set of all the parameters encoded into the url.
  15710. E.g. for the url "www.fish.com?type=haddock&amount=some+fish", this array would
  15711. contain two pairs: "type" => "haddock" and "amount" => "some fish".
  15712. The values returned will have been cleaned up to remove any escape characters.
  15713. @see getNamedParameter, withParameter
  15714. */
  15715. const StringPairArray& getParameters() const;
  15716. /** Returns the set of files that should be uploaded as part of a POST operation.
  15717. This is the set of files that were added to the URL with the withFileToUpload()
  15718. method.
  15719. */
  15720. const StringPairArray& getFilesToUpload() const;
  15721. /** Returns the set of mime types associated with each of the upload files.
  15722. */
  15723. const StringPairArray& getMimeTypesOfUploadFiles() const;
  15724. /** Returns a copy of this URL, with a block of data to send as the POST data.
  15725. If you're setting the POST data, be careful not to have any parameters set
  15726. as well, otherwise it'll all get thrown in together, and might not have the
  15727. desired effect.
  15728. If the URL already contains some POST data, this will replace it, rather
  15729. than being appended to it.
  15730. This data will only be used if you specify a post operation when you call
  15731. createInputStream().
  15732. */
  15733. const URL withPOSTData (const String& postData) const;
  15734. /** Returns the data that was set using withPOSTData().
  15735. */
  15736. String getPostData() const { return postData; }
  15737. /** Tries to launch the system's default browser to open the URL.
  15738. Returns true if this seems to have worked.
  15739. */
  15740. bool launchInDefaultBrowser() const;
  15741. /** Takes a guess as to whether a string might be a valid website address.
  15742. This isn't foolproof!
  15743. */
  15744. static bool isProbablyAWebsiteURL (const String& possibleURL);
  15745. /** Takes a guess as to whether a string might be a valid email address.
  15746. This isn't foolproof!
  15747. */
  15748. static bool isProbablyAnEmailAddress (const String& possibleEmailAddress);
  15749. /** This callback function can be used by the createInputStream() method.
  15750. It allows your app to receive progress updates during a lengthy POST operation. If you
  15751. want to continue the operation, this should return true, or false to abort.
  15752. */
  15753. typedef bool (OpenStreamProgressCallback) (void* context, int bytesSent, int totalBytes);
  15754. /** Attempts to open a stream that can read from this URL.
  15755. @param usePostCommand if true, it will try to do use a http 'POST' to pass
  15756. the paramters, otherwise it'll encode them into the
  15757. URL and do a 'GET'.
  15758. @param progressCallback if this is non-zero, it lets you supply a callback function
  15759. to keep track of the operation's progress. This can be useful
  15760. for lengthy POST operations, so that you can provide user feedback.
  15761. @param progressCallbackContext if a callback is specified, this value will be passed to
  15762. the function
  15763. @param extraHeaders if not empty, this string is appended onto the headers that
  15764. are used for the request. It must therefore be a valid set of HTML
  15765. header directives, separated by newlines.
  15766. @param connectionTimeOutMs if 0, this will use whatever default setting the OS chooses. If
  15767. a negative number, it will be infinite. Otherwise it specifies a
  15768. time in milliseconds.
  15769. @param responseHeaders if this is non-zero, all the (key, value) pairs received as headers
  15770. in the response will be stored in this array
  15771. @returns an input stream that the caller must delete, or a null pointer if there was an
  15772. error trying to open it.
  15773. */
  15774. InputStream* createInputStream (bool usePostCommand,
  15775. OpenStreamProgressCallback* progressCallback = nullptr,
  15776. void* progressCallbackContext = nullptr,
  15777. const String& extraHeaders = String::empty,
  15778. int connectionTimeOutMs = 0,
  15779. StringPairArray* responseHeaders = nullptr) const;
  15780. /** Tries to download the entire contents of this URL into a binary data block.
  15781. If it succeeds, this will return true and append the data it read onto the end
  15782. of the memory block.
  15783. @param destData the memory block to append the new data to
  15784. @param usePostCommand whether to use a POST command to get the data (uses
  15785. a GET command if this is false)
  15786. @see readEntireTextStream, readEntireXmlStream
  15787. */
  15788. bool readEntireBinaryStream (MemoryBlock& destData,
  15789. bool usePostCommand = false) const;
  15790. /** Tries to download the entire contents of this URL as a string.
  15791. If it fails, this will return an empty string, otherwise it will return the
  15792. contents of the downloaded file. If you need to distinguish between a read
  15793. operation that fails and one that returns an empty string, you'll need to use
  15794. a different method, such as readEntireBinaryStream().
  15795. @param usePostCommand whether to use a POST command to get the data (uses
  15796. a GET command if this is false)
  15797. @see readEntireBinaryStream, readEntireXmlStream
  15798. */
  15799. String readEntireTextStream (bool usePostCommand = false) const;
  15800. /** Tries to download the entire contents of this URL and parse it as XML.
  15801. If it fails, or if the text that it reads can't be parsed as XML, this will
  15802. return 0.
  15803. When it returns a valid XmlElement object, the caller is responsibile for deleting
  15804. this object when no longer needed.
  15805. @param usePostCommand whether to use a POST command to get the data (uses
  15806. a GET command if this is false)
  15807. @see readEntireBinaryStream, readEntireTextStream
  15808. */
  15809. XmlElement* readEntireXmlStream (bool usePostCommand = false) const;
  15810. /** Adds escape sequences to a string to encode any characters that aren't
  15811. legal in a URL.
  15812. E.g. any spaces will be replaced with "%20".
  15813. This is the opposite of removeEscapeChars().
  15814. If isParameter is true, it means that the string is going to be used
  15815. as a parameter, so it also encodes '$' and ',' (which would otherwise
  15816. be legal in a URL.
  15817. @see removeEscapeChars
  15818. */
  15819. static String addEscapeChars (const String& stringToAddEscapeCharsTo,
  15820. bool isParameter);
  15821. /** Replaces any escape character sequences in a string with their original
  15822. character codes.
  15823. E.g. any instances of "%20" will be replaced by a space.
  15824. This is the opposite of addEscapeChars().
  15825. @see addEscapeChars
  15826. */
  15827. static String removeEscapeChars (const String& stringToRemoveEscapeCharsFrom);
  15828. private:
  15829. String url, postData;
  15830. StringPairArray parameters, filesToUpload, mimeTypes;
  15831. static InputStream* createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  15832. OpenStreamProgressCallback* progressCallback,
  15833. void* progressCallbackContext, const String& headers,
  15834. const int timeOutMs, StringPairArray* responseHeaders);
  15835. JUCE_LEAK_DETECTOR (URL);
  15836. };
  15837. #endif // __JUCE_URL_JUCEHEADER__
  15838. /*** End of inlined file: juce_URL.h ***/
  15839. #endif
  15840. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  15841. /*** Start of inlined file: juce_BufferedInputStream.h ***/
  15842. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  15843. #define __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  15844. /*** Start of inlined file: juce_OptionalScopedPointer.h ***/
  15845. #ifndef __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  15846. #define __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  15847. /**
  15848. Holds a pointer to an object which can optionally be deleted when this pointer
  15849. goes out of scope.
  15850. This acts in many ways like a ScopedPointer, but allows you to specify whether or
  15851. not the object is deleted.
  15852. @see ScopedPointer
  15853. */
  15854. template <class ObjectType>
  15855. class OptionalScopedPointer
  15856. {
  15857. public:
  15858. /** Creates an empty OptionalScopedPointer. */
  15859. OptionalScopedPointer() : shouldDelete (false) {}
  15860. /** Creates an OptionalScopedPointer to point to a given object, and specifying whether
  15861. the OptionalScopedPointer will delete it.
  15862. If takeOwnership is true, then the OptionalScopedPointer will act like a ScopedPointer,
  15863. deleting the object when it is itself deleted. If this parameter is false, then the
  15864. OptionalScopedPointer just holds a normal pointer to the object, and won't delete it.
  15865. */
  15866. OptionalScopedPointer (ObjectType* objectToHold, bool takeOwnership)
  15867. : object (objectToHold), shouldDelete (takeOwnership)
  15868. {
  15869. }
  15870. /** Takes ownership of the object that another OptionalScopedPointer holds.
  15871. Like a normal ScopedPointer, the objectToTransferFrom object will become null,
  15872. as ownership of the managed object is transferred to this object.
  15873. The flag to indicate whether or not to delete the managed object is also
  15874. copied from the source object.
  15875. */
  15876. OptionalScopedPointer (OptionalScopedPointer& objectToTransferFrom)
  15877. : object (objectToTransferFrom.release()),
  15878. shouldDelete (objectToTransferFrom.shouldDelete)
  15879. {
  15880. }
  15881. /** Takes ownership of the object that another OptionalScopedPointer holds.
  15882. Like a normal ScopedPointer, the objectToTransferFrom object will become null,
  15883. as ownership of the managed object is transferred to this object.
  15884. The ownership flag that says whether or not to delete the managed object is also
  15885. copied from the source object.
  15886. */
  15887. OptionalScopedPointer& operator= (OptionalScopedPointer& objectToTransferFrom)
  15888. {
  15889. if (object != objectToTransferFrom.object)
  15890. {
  15891. clear();
  15892. object = objectToTransferFrom.object;
  15893. }
  15894. shouldDelete = objectToTransferFrom.shouldDelete;
  15895. return *this;
  15896. }
  15897. /** The destructor may or may not delete the object that is being held, depending on the
  15898. takeOwnership flag that was specified when the object was first passed into an
  15899. OptionalScopedPointer constructor.
  15900. */
  15901. ~OptionalScopedPointer()
  15902. {
  15903. clear();
  15904. }
  15905. /** Returns the object that this pointer is managing. */
  15906. inline operator ObjectType*() const noexcept { return object; }
  15907. /** Returns the object that this pointer is managing. */
  15908. inline ObjectType& operator*() const noexcept { return *object; }
  15909. /** Lets you access methods and properties of the object that this pointer is holding. */
  15910. inline ObjectType* operator->() const noexcept { return object; }
  15911. /** Removes the current object from this OptionalScopedPointer without deleting it.
  15912. This will return the current object, and set this OptionalScopedPointer to a null pointer.
  15913. */
  15914. ObjectType* release() noexcept { return object.release(); }
  15915. /** Resets this pointer to null, possibly deleting the object that it holds, if it has
  15916. ownership of it.
  15917. */
  15918. void clear()
  15919. {
  15920. if (! shouldDelete)
  15921. object.release();
  15922. }
  15923. /** Swaps this object with another OptionalScopedPointer.
  15924. The two objects simply exchange their states.
  15925. */
  15926. void swapWith (OptionalScopedPointer<ObjectType>& other) noexcept
  15927. {
  15928. object.swapWith (other.object);
  15929. std::swap (shouldDelete, other.shouldDelete);
  15930. }
  15931. private:
  15932. ScopedPointer<ObjectType> object;
  15933. bool shouldDelete;
  15934. };
  15935. #endif // __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  15936. /*** End of inlined file: juce_OptionalScopedPointer.h ***/
  15937. /** Wraps another input stream, and reads from it using an intermediate buffer
  15938. If you're using an input stream such as a file input stream, and making lots of
  15939. small read accesses to it, it's probably sensible to wrap it in one of these,
  15940. so that the source stream gets accessed in larger chunk sizes, meaning less
  15941. work for the underlying stream.
  15942. */
  15943. class JUCE_API BufferedInputStream : public InputStream
  15944. {
  15945. public:
  15946. /** Creates a BufferedInputStream from an input source.
  15947. @param sourceStream the source stream to read from
  15948. @param bufferSize the size of reservoir to use to buffer the source
  15949. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  15950. deleted by this object when it is itself deleted.
  15951. */
  15952. BufferedInputStream (InputStream* sourceStream,
  15953. int bufferSize,
  15954. bool deleteSourceWhenDestroyed);
  15955. /** Creates a BufferedInputStream from an input source.
  15956. @param sourceStream the source stream to read from - the source stream must not
  15957. be deleted until this object has been destroyed.
  15958. @param bufferSize the size of reservoir to use to buffer the source
  15959. */
  15960. BufferedInputStream (InputStream& sourceStream, int bufferSize);
  15961. /** Destructor.
  15962. This may also delete the source stream, if that option was chosen when the
  15963. buffered stream was created.
  15964. */
  15965. ~BufferedInputStream();
  15966. int64 getTotalLength();
  15967. int64 getPosition();
  15968. bool setPosition (int64 newPosition);
  15969. int read (void* destBuffer, int maxBytesToRead);
  15970. String readString();
  15971. bool isExhausted();
  15972. private:
  15973. OptionalScopedPointer<InputStream> source;
  15974. int bufferSize;
  15975. int64 position, lastReadPos, bufferStart, bufferOverlap;
  15976. HeapBlock <char> buffer;
  15977. void ensureBuffered();
  15978. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BufferedInputStream);
  15979. };
  15980. #endif // __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  15981. /*** End of inlined file: juce_BufferedInputStream.h ***/
  15982. #endif
  15983. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  15984. /*** Start of inlined file: juce_FileInputSource.h ***/
  15985. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  15986. #define __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  15987. /**
  15988. A type of InputSource that represents a normal file.
  15989. @see InputSource
  15990. */
  15991. class JUCE_API FileInputSource : public InputSource
  15992. {
  15993. public:
  15994. FileInputSource (const File& file, bool useFileTimeInHashGeneration = false);
  15995. ~FileInputSource();
  15996. InputStream* createInputStream();
  15997. InputStream* createInputStreamFor (const String& relatedItemPath);
  15998. int64 hashCode() const;
  15999. private:
  16000. const File file;
  16001. bool useFileTimeInHashGeneration;
  16002. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileInputSource);
  16003. };
  16004. #endif // __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  16005. /*** End of inlined file: juce_FileInputSource.h ***/
  16006. #endif
  16007. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  16008. /*** Start of inlined file: juce_GZIPCompressorOutputStream.h ***/
  16009. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  16010. #define __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  16011. /**
  16012. A stream which uses zlib to compress the data written into it.
  16013. @see GZIPDecompressorInputStream
  16014. */
  16015. class JUCE_API GZIPCompressorOutputStream : public OutputStream
  16016. {
  16017. public:
  16018. /** Creates a compression stream.
  16019. @param destStream the stream into which the compressed data should
  16020. be written
  16021. @param compressionLevel how much to compress the data, between 1 and 9, where
  16022. 1 is the fastest/lowest compression, and 9 is the
  16023. slowest/highest compression. Any value outside this range
  16024. indicates that a default compression level should be used.
  16025. @param deleteDestStreamWhenDestroyed whether or not to delete the destStream object when
  16026. this stream is destroyed
  16027. @param windowBits this is used internally to change the window size used
  16028. by zlib - leave it as 0 unless you specifically need to set
  16029. its value for some reason
  16030. */
  16031. GZIPCompressorOutputStream (OutputStream* destStream,
  16032. int compressionLevel = 0,
  16033. bool deleteDestStreamWhenDestroyed = false,
  16034. int windowBits = 0);
  16035. /** Destructor. */
  16036. ~GZIPCompressorOutputStream();
  16037. void flush();
  16038. int64 getPosition();
  16039. bool setPosition (int64 newPosition);
  16040. bool write (const void* destBuffer, int howMany);
  16041. /** These are preset values that can be used for the constructor's windowBits paramter.
  16042. For more info about this, see the zlib documentation for its windowBits parameter.
  16043. */
  16044. enum WindowBitsValues
  16045. {
  16046. windowBitsRaw = -15,
  16047. windowBitsGZIP = 15 + 16
  16048. };
  16049. private:
  16050. OptionalScopedPointer<OutputStream> destStream;
  16051. HeapBlock <uint8> buffer;
  16052. class GZIPCompressorHelper;
  16053. friend class ScopedPointer <GZIPCompressorHelper>;
  16054. ScopedPointer <GZIPCompressorHelper> helper;
  16055. bool doNextBlock();
  16056. void flushInternal();
  16057. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GZIPCompressorOutputStream);
  16058. };
  16059. #endif // __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  16060. /*** End of inlined file: juce_GZIPCompressorOutputStream.h ***/
  16061. #endif
  16062. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  16063. /*** Start of inlined file: juce_GZIPDecompressorInputStream.h ***/
  16064. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  16065. #define __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  16066. /**
  16067. This stream will decompress a source-stream using zlib.
  16068. Tip: if you're reading lots of small items from one of these streams, you
  16069. can increase the performance enormously by passing it through a
  16070. BufferedInputStream, so that it has to read larger blocks less often.
  16071. @see GZIPCompressorOutputStream
  16072. */
  16073. class JUCE_API GZIPDecompressorInputStream : public InputStream
  16074. {
  16075. public:
  16076. /** Creates a decompressor stream.
  16077. @param sourceStream the stream to read from
  16078. @param deleteSourceWhenDestroyed whether or not to delete the source stream
  16079. when this object is destroyed
  16080. @param noWrap this is used internally by the ZipFile class
  16081. and should be ignored by user applications
  16082. @param uncompressedStreamLength if the creator knows the length that the
  16083. uncompressed stream will be, then it can supply this
  16084. value, which will be returned by getTotalLength()
  16085. */
  16086. GZIPDecompressorInputStream (InputStream* sourceStream,
  16087. bool deleteSourceWhenDestroyed,
  16088. bool noWrap = false,
  16089. int64 uncompressedStreamLength = -1);
  16090. /** Creates a decompressor stream.
  16091. @param sourceStream the stream to read from - the source stream must not be
  16092. deleted until this object has been destroyed
  16093. */
  16094. GZIPDecompressorInputStream (InputStream& sourceStream);
  16095. /** Destructor. */
  16096. ~GZIPDecompressorInputStream();
  16097. int64 getPosition();
  16098. bool setPosition (int64 pos);
  16099. int64 getTotalLength();
  16100. bool isExhausted();
  16101. int read (void* destBuffer, int maxBytesToRead);
  16102. private:
  16103. OptionalScopedPointer<InputStream> sourceStream;
  16104. const int64 uncompressedStreamLength;
  16105. const bool noWrap;
  16106. bool isEof;
  16107. int activeBufferSize;
  16108. int64 originalSourcePos, currentPos;
  16109. HeapBlock <uint8> buffer;
  16110. class GZIPDecompressHelper;
  16111. friend class ScopedPointer <GZIPDecompressHelper>;
  16112. ScopedPointer <GZIPDecompressHelper> helper;
  16113. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GZIPDecompressorInputStream);
  16114. };
  16115. #endif // __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  16116. /*** End of inlined file: juce_GZIPDecompressorInputStream.h ***/
  16117. #endif
  16118. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  16119. #endif
  16120. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  16121. #endif
  16122. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  16123. /*** Start of inlined file: juce_MemoryInputStream.h ***/
  16124. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  16125. #define __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  16126. /**
  16127. Allows a block of data and to be accessed as a stream.
  16128. This can either be used to refer to a shared block of memory, or can make its
  16129. own internal copy of the data when the MemoryInputStream is created.
  16130. */
  16131. class JUCE_API MemoryInputStream : public InputStream
  16132. {
  16133. public:
  16134. /** Creates a MemoryInputStream.
  16135. @param sourceData the block of data to use as the stream's source
  16136. @param sourceDataSize the number of bytes in the source data block
  16137. @param keepInternalCopyOfData if false, the stream will just keep a pointer to
  16138. the source data, so this data shouldn't be changed
  16139. for the lifetime of the stream; if this parameter is
  16140. true, the stream will make its own copy of the
  16141. data and use that.
  16142. */
  16143. MemoryInputStream (const void* sourceData,
  16144. size_t sourceDataSize,
  16145. bool keepInternalCopyOfData);
  16146. /** Creates a MemoryInputStream.
  16147. @param data a block of data to use as the stream's source
  16148. @param keepInternalCopyOfData if false, the stream will just keep a reference to
  16149. the source data, so this data shouldn't be changed
  16150. for the lifetime of the stream; if this parameter is
  16151. true, the stream will make its own copy of the
  16152. data and use that.
  16153. */
  16154. MemoryInputStream (const MemoryBlock& data,
  16155. bool keepInternalCopyOfData);
  16156. /** Destructor. */
  16157. ~MemoryInputStream();
  16158. int64 getPosition();
  16159. bool setPosition (int64 pos);
  16160. int64 getTotalLength();
  16161. bool isExhausted();
  16162. int read (void* destBuffer, int maxBytesToRead);
  16163. private:
  16164. const char* data;
  16165. size_t dataSize, position;
  16166. HeapBlock<char> internalCopy;
  16167. void createInternalCopy();
  16168. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MemoryInputStream);
  16169. };
  16170. #endif // __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  16171. /*** End of inlined file: juce_MemoryInputStream.h ***/
  16172. #endif
  16173. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  16174. /*** Start of inlined file: juce_MemoryOutputStream.h ***/
  16175. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  16176. #define __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  16177. /**
  16178. Writes data to an internal memory buffer, which grows as required.
  16179. The data that was written into the stream can then be accessed later as
  16180. a contiguous block of memory.
  16181. */
  16182. class JUCE_API MemoryOutputStream : public OutputStream
  16183. {
  16184. public:
  16185. /** Creates an empty memory stream ready for writing into.
  16186. @param initialSize the intial amount of capacity to allocate for writing into
  16187. */
  16188. MemoryOutputStream (size_t initialSize = 256);
  16189. /** Creates a memory stream for writing into into a pre-existing MemoryBlock object.
  16190. Note that the destination block will always be larger than the amount of data
  16191. that has been written to the stream, because the MemoryOutputStream keeps some
  16192. spare capactity at its end. To trim the block's size down to fit the actual
  16193. data, call flush(), or delete the MemoryOutputStream.
  16194. @param memoryBlockToWriteTo the block into which new data will be written.
  16195. @param appendToExistingBlockContent if this is true, the contents of the block will be
  16196. kept, and new data will be appended to it. If false,
  16197. the block will be cleared before use
  16198. */
  16199. MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  16200. bool appendToExistingBlockContent);
  16201. /** Destructor.
  16202. This will free any data that was written to it.
  16203. */
  16204. ~MemoryOutputStream();
  16205. /** Returns a pointer to the data that has been written to the stream.
  16206. @see getDataSize
  16207. */
  16208. const void* getData() const noexcept;
  16209. /** Returns the number of bytes of data that have been written to the stream.
  16210. @see getData
  16211. */
  16212. size_t getDataSize() const noexcept { return size; }
  16213. /** Resets the stream, clearing any data that has been written to it so far. */
  16214. void reset() noexcept;
  16215. /** Increases the internal storage capacity to be able to contain at least the specified
  16216. amount of data without needing to be resized.
  16217. */
  16218. void preallocate (size_t bytesToPreallocate);
  16219. /** Returns a String created from the (UTF8) data that has been written to the stream. */
  16220. String toUTF8() const;
  16221. /** Attempts to detect the encoding of the data and convert it to a string.
  16222. @see String::createStringFromData
  16223. */
  16224. String toString() const;
  16225. /** If the stream is writing to a user-supplied MemoryBlock, this will trim any excess
  16226. capacity off the block, so that its length matches the amount of actual data that
  16227. has been written so far.
  16228. */
  16229. void flush();
  16230. bool write (const void* buffer, int howMany);
  16231. int64 getPosition() { return position; }
  16232. bool setPosition (int64 newPosition);
  16233. int writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite);
  16234. void writeRepeatedByte (uint8 byte, int numTimesToRepeat);
  16235. private:
  16236. MemoryBlock& data;
  16237. MemoryBlock internalBlock;
  16238. size_t position, size;
  16239. void trimExternalBlockSize();
  16240. void prepareToWrite (int numBytes);
  16241. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MemoryOutputStream);
  16242. };
  16243. /** Copies all the data that has been written to a MemoryOutputStream into another stream. */
  16244. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead);
  16245. #endif // __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  16246. /*** End of inlined file: juce_MemoryOutputStream.h ***/
  16247. #endif
  16248. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  16249. #endif
  16250. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  16251. /*** Start of inlined file: juce_SubregionStream.h ***/
  16252. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  16253. #define __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  16254. /** Wraps another input stream, and reads from a specific part of it.
  16255. This lets you take a subsection of a stream and present it as an entire
  16256. stream in its own right.
  16257. */
  16258. class JUCE_API SubregionStream : public InputStream
  16259. {
  16260. public:
  16261. /** Creates a SubregionStream from an input source.
  16262. @param sourceStream the source stream to read from
  16263. @param startPositionInSourceStream this is the position in the source stream that
  16264. corresponds to position 0 in this stream
  16265. @param lengthOfSourceStream this specifies the maximum number of bytes
  16266. from the source stream that will be passed through
  16267. by this stream. When the position of this stream
  16268. exceeds lengthOfSourceStream, it will cause an end-of-stream.
  16269. If the length passed in here is greater than the length
  16270. of the source stream (as returned by getTotalLength()),
  16271. then the smaller value will be used.
  16272. Passing a negative value for this parameter means it
  16273. will keep reading until the source's end-of-stream.
  16274. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  16275. deleted by this object when it is itself deleted.
  16276. */
  16277. SubregionStream (InputStream* sourceStream,
  16278. int64 startPositionInSourceStream,
  16279. int64 lengthOfSourceStream,
  16280. bool deleteSourceWhenDestroyed);
  16281. /** Destructor.
  16282. This may also delete the source stream, if that option was chosen when the
  16283. buffered stream was created.
  16284. */
  16285. ~SubregionStream();
  16286. int64 getTotalLength();
  16287. int64 getPosition();
  16288. bool setPosition (int64 newPosition);
  16289. int read (void* destBuffer, int maxBytesToRead);
  16290. bool isExhausted();
  16291. private:
  16292. OptionalScopedPointer<InputStream> source;
  16293. const int64 startPositionInSourceStream, lengthOfSourceStream;
  16294. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SubregionStream);
  16295. };
  16296. #endif // __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  16297. /*** End of inlined file: juce_SubregionStream.h ***/
  16298. #endif
  16299. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  16300. #endif
  16301. #ifndef __JUCE_EXPRESSION_JUCEHEADER__
  16302. /*** Start of inlined file: juce_Expression.h ***/
  16303. #ifndef __JUCE_EXPRESSION_JUCEHEADER__
  16304. #define __JUCE_EXPRESSION_JUCEHEADER__
  16305. /**
  16306. A class for dynamically evaluating simple numeric expressions.
  16307. This class can parse a simple C-style string expression involving floating point
  16308. numbers, named symbols and functions. The basic arithmetic operations of +, -, *, /
  16309. are supported, as well as parentheses, and any alphanumeric identifiers are
  16310. assumed to be named symbols which will be resolved when the expression is
  16311. evaluated.
  16312. Expressions which use identifiers and functions require a subclass of
  16313. Expression::Scope to be supplied when evaluating them, and this object
  16314. is expected to be able to resolve the symbol names and perform the functions that
  16315. are used.
  16316. */
  16317. class JUCE_API Expression
  16318. {
  16319. public:
  16320. /** Creates a simple expression with a value of 0. */
  16321. Expression();
  16322. /** Destructor. */
  16323. ~Expression();
  16324. /** Creates a simple expression with a specified constant value. */
  16325. explicit Expression (double constant);
  16326. /** Creates a copy of an expression. */
  16327. Expression (const Expression& other);
  16328. /** Copies another expression. */
  16329. Expression& operator= (const Expression& other);
  16330. /** Creates an expression by parsing a string.
  16331. If there's a syntax error in the string, this will throw a ParseError exception.
  16332. @throws ParseError
  16333. */
  16334. explicit Expression (const String& stringToParse);
  16335. /** Returns a string version of the expression. */
  16336. String toString() const;
  16337. /** Returns an expression which is an addtion operation of two existing expressions. */
  16338. Expression operator+ (const Expression& other) const;
  16339. /** Returns an expression which is a subtraction operation of two existing expressions. */
  16340. Expression operator- (const Expression& other) const;
  16341. /** Returns an expression which is a multiplication operation of two existing expressions. */
  16342. Expression operator* (const Expression& other) const;
  16343. /** Returns an expression which is a division operation of two existing expressions. */
  16344. Expression operator/ (const Expression& other) const;
  16345. /** Returns an expression which performs a negation operation on an existing expression. */
  16346. Expression operator-() const;
  16347. /** Returns an Expression which is an identifier reference. */
  16348. static Expression symbol (const String& symbol);
  16349. /** Returns an Expression which is a function call. */
  16350. static Expression function (const String& functionName, const Array<Expression>& parameters);
  16351. /** Returns an Expression which parses a string from a character pointer, and updates the pointer
  16352. to indicate where it finished.
  16353. The pointer is incremented so that on return, it indicates the character that follows
  16354. the end of the expression that was parsed.
  16355. If there's a syntax error in the string, this will throw a ParseError exception.
  16356. @throws ParseError
  16357. */
  16358. static Expression parse (String::CharPointerType& stringToParse);
  16359. /** When evaluating an Expression object, this class is used to resolve symbols and
  16360. perform functions that the expression uses.
  16361. */
  16362. class JUCE_API Scope
  16363. {
  16364. public:
  16365. Scope();
  16366. virtual ~Scope();
  16367. /** Returns some kind of globally unique ID that identifies this scope. */
  16368. virtual String getScopeUID() const;
  16369. /** Returns the value of a symbol.
  16370. If the symbol is unknown, this can throw an Expression::EvaluationError exception.
  16371. The member value is set to the part of the symbol that followed the dot, if there is
  16372. one, e.g. for "foo.bar", symbol = "foo" and member = "bar".
  16373. @throws Expression::EvaluationError
  16374. */
  16375. virtual Expression getSymbolValue (const String& symbol) const;
  16376. /** Executes a named function.
  16377. If the function name is unknown, this can throw an Expression::EvaluationError exception.
  16378. @throws Expression::EvaluationError
  16379. */
  16380. virtual double evaluateFunction (const String& functionName,
  16381. const double* parameters, int numParameters) const;
  16382. /** Used as a callback by the Scope::visitRelativeScope() method.
  16383. You should never create an instance of this class yourself, it's used by the
  16384. expression evaluation code.
  16385. */
  16386. class Visitor
  16387. {
  16388. public:
  16389. virtual ~Visitor() {}
  16390. virtual void visit (const Scope&) = 0;
  16391. };
  16392. /** Creates a Scope object for a named scope, and then calls a visitor
  16393. to do some kind of processing with this new scope.
  16394. If the name is valid, this method must create a suitable (temporary) Scope
  16395. object to represent it, and must call the Visitor::visit() method with this
  16396. new scope.
  16397. */
  16398. virtual void visitRelativeScope (const String& scopeName, Visitor& visitor) const;
  16399. };
  16400. /** Evaluates this expression, without using a Scope.
  16401. Without a Scope, no symbols can be used, and only basic functions such as sin, cos, tan,
  16402. min, max are available.
  16403. To find out about any errors during evaluation, use the other version of this method which
  16404. takes a String parameter.
  16405. */
  16406. double evaluate() const;
  16407. /** Evaluates this expression, providing a scope that should be able to evaluate any symbols
  16408. or functions that it uses.
  16409. To find out about any errors during evaluation, use the other version of this method which
  16410. takes a String parameter.
  16411. */
  16412. double evaluate (const Scope& scope) const;
  16413. /** Evaluates this expression, providing a scope that should be able to evaluate any symbols
  16414. or functions that it uses.
  16415. */
  16416. double evaluate (const Scope& scope, String& evaluationError) const;
  16417. /** Attempts to return an expression which is a copy of this one, but with a constant adjusted
  16418. to make the expression resolve to a target value.
  16419. E.g. if the expression is "x + 10" and x is 5, then asking for a target value of 8 will return
  16420. the expression "x + 3". Obviously some expressions can't be reversed in this way, in which
  16421. case they might just be adjusted by adding a constant to the original expression.
  16422. @throws Expression::EvaluationError
  16423. */
  16424. Expression adjustedToGiveNewResult (double targetValue, const Scope& scope) const;
  16425. /** Represents a symbol that is used in an Expression. */
  16426. struct Symbol
  16427. {
  16428. Symbol (const String& scopeUID, const String& symbolName);
  16429. bool operator== (const Symbol&) const noexcept;
  16430. bool operator!= (const Symbol&) const noexcept;
  16431. String scopeUID; /**< The unique ID of the Scope that contains this symbol. */
  16432. String symbolName; /**< The name of the symbol. */
  16433. };
  16434. /** Returns a copy of this expression in which all instances of a given symbol have been renamed. */
  16435. Expression withRenamedSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope) const;
  16436. /** Returns true if this expression makes use of the specified symbol.
  16437. If a suitable scope is supplied, the search will dereference and recursively check
  16438. all symbols, so that it can be determined whether this expression relies on the given
  16439. symbol at any level in its evaluation. If the scope parameter is null, this just checks
  16440. whether the expression contains any direct references to the symbol.
  16441. @throws Expression::EvaluationError
  16442. */
  16443. bool referencesSymbol (const Symbol& symbol, const Scope& scope) const;
  16444. /** Returns true if this expression contains any symbols. */
  16445. bool usesAnySymbols() const;
  16446. /** Returns a list of all symbols that may be needed to resolve this expression in the given scope. */
  16447. void findReferencedSymbols (Array<Symbol>& results, const Scope& scope) const;
  16448. /** An exception that can be thrown by Expression::parse(). */
  16449. class ParseError : public std::exception
  16450. {
  16451. public:
  16452. ParseError (const String& message);
  16453. String description;
  16454. };
  16455. /** Expression type.
  16456. @see Expression::getType()
  16457. */
  16458. enum Type
  16459. {
  16460. constantType,
  16461. functionType,
  16462. operatorType,
  16463. symbolType
  16464. };
  16465. /** Returns the type of this expression. */
  16466. Type getType() const noexcept;
  16467. /** If this expression is a symbol, function or operator, this returns its identifier. */
  16468. String getSymbolOrFunction() const;
  16469. /** Returns the number of inputs to this expression.
  16470. @see getInput
  16471. */
  16472. int getNumInputs() const;
  16473. /** Retrieves one of the inputs to this expression.
  16474. @see getNumInputs
  16475. */
  16476. Expression getInput (int index) const;
  16477. private:
  16478. class Term;
  16479. class Helpers;
  16480. friend class Term;
  16481. friend class Helpers;
  16482. friend class ScopedPointer<Term>;
  16483. friend class ReferenceCountedObjectPtr<Term>;
  16484. ReferenceCountedObjectPtr<Term> term;
  16485. explicit Expression (Term* term);
  16486. };
  16487. #endif // __JUCE_EXPRESSION_JUCEHEADER__
  16488. /*** End of inlined file: juce_Expression.h ***/
  16489. #endif
  16490. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  16491. #endif
  16492. #ifndef __JUCE_RANDOM_JUCEHEADER__
  16493. /*** Start of inlined file: juce_Random.h ***/
  16494. #ifndef __JUCE_RANDOM_JUCEHEADER__
  16495. #define __JUCE_RANDOM_JUCEHEADER__
  16496. /**
  16497. A random number generator.
  16498. You can create a Random object and use it to generate a sequence of random numbers.
  16499. As a handy shortcut to avoid having to create and seed one yourself, you can call
  16500. Random::getSystemRandom() to return a global RNG that is seeded randomly when the
  16501. app launches.
  16502. */
  16503. class JUCE_API Random
  16504. {
  16505. public:
  16506. /** Creates a Random object based on a seed value.
  16507. For a given seed value, the subsequent numbers generated by this object
  16508. will be predictable, so a good idea is to set this value based
  16509. on the time, e.g.
  16510. new Random (Time::currentTimeMillis())
  16511. */
  16512. explicit Random (int64 seedValue) noexcept;
  16513. /** Creates a Random object using a random seed value.
  16514. Internally, this calls setSeedRandomly() to randomise the seed.
  16515. */
  16516. Random();
  16517. /** Destructor. */
  16518. ~Random() noexcept;
  16519. /** Returns the next random 32 bit integer.
  16520. @returns a random integer from the full range 0x80000000 to 0x7fffffff
  16521. */
  16522. int nextInt() noexcept;
  16523. /** Returns the next random number, limited to a given range.
  16524. @returns a random integer between 0 (inclusive) and maxValue (exclusive).
  16525. */
  16526. int nextInt (int maxValue) noexcept;
  16527. /** Returns the next 64-bit random number.
  16528. @returns a random integer from the full range 0x8000000000000000 to 0x7fffffffffffffff
  16529. */
  16530. int64 nextInt64() noexcept;
  16531. /** Returns the next random floating-point number.
  16532. @returns a random value in the range 0 to 1.0
  16533. */
  16534. float nextFloat() noexcept;
  16535. /** Returns the next random floating-point number.
  16536. @returns a random value in the range 0 to 1.0
  16537. */
  16538. double nextDouble() noexcept;
  16539. /** Returns the next random boolean value.
  16540. */
  16541. bool nextBool() noexcept;
  16542. /** Returns a BigInteger containing a random number.
  16543. @returns a random value in the range 0 to (maximumValue - 1).
  16544. */
  16545. BigInteger nextLargeNumber (const BigInteger& maximumValue);
  16546. /** Sets a range of bits in a BigInteger to random values. */
  16547. void fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits);
  16548. /** To avoid the overhead of having to create a new Random object whenever
  16549. you need a number, this is a shared application-wide object that
  16550. can be used.
  16551. It's not thread-safe though, so threads should use their own Random object.
  16552. */
  16553. static Random& getSystemRandom() noexcept;
  16554. /** Resets this Random object to a given seed value. */
  16555. void setSeed (int64 newSeed) noexcept;
  16556. /** Merges this object's seed with another value.
  16557. This sets the seed to be a value created by combining the current seed and this
  16558. new value.
  16559. */
  16560. void combineSeed (int64 seedValue) noexcept;
  16561. /** Reseeds this generator using a value generated from various semi-random system
  16562. properties like the current time, etc.
  16563. Because this function convolves the time with the last seed value, calling
  16564. it repeatedly will increase the randomness of the final result.
  16565. */
  16566. void setSeedRandomly();
  16567. private:
  16568. int64 seed;
  16569. JUCE_LEAK_DETECTOR (Random);
  16570. };
  16571. #endif // __JUCE_RANDOM_JUCEHEADER__
  16572. /*** End of inlined file: juce_Random.h ***/
  16573. #endif
  16574. #ifndef __JUCE_RANGE_JUCEHEADER__
  16575. #endif
  16576. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  16577. #endif
  16578. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  16579. #endif
  16580. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  16581. #endif
  16582. #ifndef __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  16583. #endif
  16584. #ifndef __JUCE_MEMORY_JUCEHEADER__
  16585. #endif
  16586. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  16587. #endif
  16588. #ifndef __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  16589. #endif
  16590. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  16591. #endif
  16592. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  16593. #endif
  16594. #ifndef __JUCE_WEAKREFERENCE_JUCEHEADER__
  16595. /*** Start of inlined file: juce_WeakReference.h ***/
  16596. #ifndef __JUCE_WEAKREFERENCE_JUCEHEADER__
  16597. #define __JUCE_WEAKREFERENCE_JUCEHEADER__
  16598. /**
  16599. This class acts as a pointer which will automatically become null if the object
  16600. to which it points is deleted.
  16601. To accomplish this, the source object needs to cooperate by performing a couple of simple tasks.
  16602. It must provide a getWeakReference() method and embed a WeakReference::Master object, which stores
  16603. a shared pointer object. It must also clear this master pointer when it's getting deleted.
  16604. E.g.
  16605. @code
  16606. class MyObject
  16607. {
  16608. public:
  16609. MyObject()
  16610. {
  16611. // If you're planning on using your WeakReferences in a multi-threaded situation, you may choose
  16612. // to call getWeakReference() here in the constructor, which will pre-initialise it, avoiding an
  16613. // (extremely unlikely) race condition that could occur if multiple threads overlap while making
  16614. // the first call to getWeakReference().
  16615. }
  16616. ~MyObject()
  16617. {
  16618. // This will zero all the references - you need to call this in your destructor.
  16619. masterReference.clear();
  16620. }
  16621. // Your object must provide a method that looks pretty much identical to this (except
  16622. // for the templated class name, of course).
  16623. const WeakReference<MyObject>::SharedRef& getWeakReference()
  16624. {
  16625. return masterReference (this);
  16626. }
  16627. private:
  16628. // You need to embed one of these inside your object. It can be private.
  16629. WeakReference<MyObject>::Master masterReference;
  16630. };
  16631. // Here's an example of using a pointer..
  16632. MyObject* n = new MyObject();
  16633. WeakReference<MyObject> myObjectRef = n;
  16634. MyObject* pointer1 = myObjectRef; // returns a valid pointer to 'n'
  16635. delete n;
  16636. MyObject* pointer2 = myObjectRef; // returns a null pointer
  16637. @endcode
  16638. @see WeakReference::Master
  16639. */
  16640. template <class ObjectType, class ReferenceCountingType = ReferenceCountedObject>
  16641. class WeakReference
  16642. {
  16643. public:
  16644. /** Creates a null SafePointer. */
  16645. inline WeakReference() noexcept {}
  16646. /** Creates a WeakReference that points at the given object. */
  16647. WeakReference (ObjectType* const object) : holder (object != nullptr ? object->getWeakReference() : nullptr) {}
  16648. /** Creates a copy of another WeakReference. */
  16649. WeakReference (const WeakReference& other) noexcept : holder (other.holder) {}
  16650. /** Copies another pointer to this one. */
  16651. WeakReference& operator= (const WeakReference& other) { holder = other.holder; return *this; }
  16652. /** Copies another pointer to this one. */
  16653. WeakReference& operator= (ObjectType* const newObject) { holder = (newObject != nullptr) ? newObject->getWeakReference() : nullptr; return *this; }
  16654. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16655. ObjectType* get() const noexcept { return holder != nullptr ? holder->get() : nullptr; }
  16656. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16657. operator ObjectType*() const noexcept { return get(); }
  16658. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16659. ObjectType* operator->() noexcept { return get(); }
  16660. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16661. const ObjectType* operator->() const noexcept { return get(); }
  16662. /** This returns true if this reference has been pointing at an object, but that object has
  16663. since been deleted.
  16664. If this reference was only ever pointing at a null pointer, this will return false. Using
  16665. operator=() to make this refer to a different object will reset this flag to match the status
  16666. of the reference from which you're copying.
  16667. */
  16668. bool wasObjectDeleted() const noexcept { return holder != nullptr && holder->get() == nullptr; }
  16669. bool operator== (ObjectType* const object) const noexcept { return get() == object; }
  16670. bool operator!= (ObjectType* const object) const noexcept { return get() != object; }
  16671. /** This class is used internally by the WeakReference class - don't use it directly
  16672. in your code!
  16673. @see WeakReference
  16674. */
  16675. class SharedPointer : public ReferenceCountingType
  16676. {
  16677. public:
  16678. explicit SharedPointer (ObjectType* const owner_) noexcept : owner (owner_) {}
  16679. inline ObjectType* get() const noexcept { return owner; }
  16680. void clearPointer() noexcept { owner = nullptr; }
  16681. private:
  16682. ObjectType* volatile owner;
  16683. JUCE_DECLARE_NON_COPYABLE (SharedPointer);
  16684. };
  16685. typedef ReferenceCountedObjectPtr<SharedPointer> SharedRef;
  16686. /**
  16687. This class is embedded inside an object to which you want to attach WeakReference pointers.
  16688. See the WeakReference class notes for an example of how to use this class.
  16689. @see WeakReference
  16690. */
  16691. class Master
  16692. {
  16693. public:
  16694. Master() noexcept {}
  16695. ~Master()
  16696. {
  16697. // You must remember to call clear() in your source object's destructor! See the notes
  16698. // for the WeakReference class for an example of how to do this.
  16699. jassert (sharedPointer == nullptr || sharedPointer->get() == nullptr);
  16700. }
  16701. /** The first call to this method will create an internal object that is shared by all weak
  16702. references to the object.
  16703. You need to call this from your main object's getWeakReference() method - see the WeakReference
  16704. class notes for an example.
  16705. */
  16706. const SharedRef& operator() (ObjectType* const object)
  16707. {
  16708. if (sharedPointer == nullptr)
  16709. {
  16710. sharedPointer = new SharedPointer (object);
  16711. }
  16712. else
  16713. {
  16714. // You're trying to create a weak reference to an object that has already been deleted!!
  16715. jassert (sharedPointer->get() != nullptr);
  16716. }
  16717. return sharedPointer;
  16718. }
  16719. /** The object that owns this master pointer should call this before it gets destroyed,
  16720. to zero all the references to this object that may be out there. See the WeakReference
  16721. class notes for an example of how to do this.
  16722. */
  16723. void clear()
  16724. {
  16725. if (sharedPointer != nullptr)
  16726. sharedPointer->clearPointer();
  16727. }
  16728. private:
  16729. SharedRef sharedPointer;
  16730. JUCE_DECLARE_NON_COPYABLE (Master);
  16731. };
  16732. private:
  16733. SharedRef holder;
  16734. };
  16735. #endif // __JUCE_WEAKREFERENCE_JUCEHEADER__
  16736. /*** End of inlined file: juce_WeakReference.h ***/
  16737. #endif
  16738. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  16739. #endif
  16740. #ifndef __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  16741. #endif
  16742. #ifndef __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  16743. #endif
  16744. #ifndef __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  16745. #endif
  16746. #ifndef __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  16747. #endif
  16748. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  16749. #endif
  16750. #ifndef __JUCE_JSON_JUCEHEADER__
  16751. /*** Start of inlined file: juce_JSON.h ***/
  16752. #ifndef __JUCE_JSON_JUCEHEADER__
  16753. #define __JUCE_JSON_JUCEHEADER__
  16754. class InputStream;
  16755. class OutputStream;
  16756. class File;
  16757. /**
  16758. Contains static methods for converting JSON-formatted text to and from var objects.
  16759. The var class is structurally compatible with JSON-formatted data, so these
  16760. functions allow you to parse JSON into a var object, and to convert a var
  16761. object to JSON-formatted text.
  16762. @see var
  16763. */
  16764. class JSON
  16765. {
  16766. public:
  16767. /** Parses a string of JSON-formatted text, and returns a result code containing
  16768. any parse errors.
  16769. This will return the parsed structure in the parsedResult parameter, and will
  16770. return a Result object to indicate whether parsing was successful, and if not,
  16771. it will contain an error message.
  16772. If you're not interested in the error message, you can use one of the other
  16773. shortcut parse methods, which simply return a var::null if the parsing fails.
  16774. */
  16775. static Result parse (const String& text, var& parsedResult);
  16776. /** Attempts to parse some JSON-formatted text, and returns the result as a var object.
  16777. If the parsing fails, this simply returns var::null - if you need to find out more
  16778. detail about the parse error, use the alternative parse() method which returns a Result.
  16779. */
  16780. static var parse (const String& text);
  16781. /** Attempts to parse some JSON-formatted text from a file, and returns the result
  16782. as a var object.
  16783. Note that this is just a short-cut for reading the entire file into a string and
  16784. parsing the result.
  16785. If the parsing fails, this simply returns var::null - if you need to find out more
  16786. detail about the parse error, use the alternative parse() method which returns a Result.
  16787. */
  16788. static var parse (const File& file);
  16789. /** Attempts to parse some JSON-formatted text from a stream, and returns the result
  16790. as a var object.
  16791. Note that this is just a short-cut for reading the entire stream into a string and
  16792. parsing the result.
  16793. If the parsing fails, this simply returns var::null - if you need to find out more
  16794. detail about the parse error, use the alternative parse() method which returns a Result.
  16795. */
  16796. static var parse (InputStream& input);
  16797. /** Returns a string which contains a JSON-formatted representation of the var object.
  16798. If allOnOneLine is true, the result will be compacted into a single line of text
  16799. with no carriage-returns. If false, it will be laid-out in a more human-readable format.
  16800. @see writeToStream
  16801. */
  16802. static String toString (const var& objectToFormat,
  16803. bool allOnOneLine = false);
  16804. /** Writes a JSON-formatted representation of the var object to the given stream.
  16805. If allOnOneLine is true, the result will be compacted into a single line of text
  16806. with no carriage-returns. If false, it will be laid-out in a more human-readable format.
  16807. @see toString
  16808. */
  16809. static void writeToStream (OutputStream& output,
  16810. const var& objectToFormat,
  16811. bool allOnOneLine = false);
  16812. private:
  16813. JSON(); // This class can't be instantiated - just use its static methods.
  16814. };
  16815. #endif // __JUCE_JSON_JUCEHEADER__
  16816. /*** End of inlined file: juce_JSON.h ***/
  16817. #endif
  16818. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  16819. /*** Start of inlined file: juce_LocalisedStrings.h ***/
  16820. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  16821. #define __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  16822. /** Used in the same way as the T(text) macro, this will attempt to translate a
  16823. string into a localised version using the LocalisedStrings class.
  16824. @see LocalisedStrings
  16825. */
  16826. #define TRANS(stringLiteral) \
  16827. JUCE_NAMESPACE::LocalisedStrings::translateWithCurrentMappings (stringLiteral)
  16828. /**
  16829. Used to convert strings to localised foreign-language versions.
  16830. This is basically a look-up table of strings and their translated equivalents.
  16831. It can be loaded from a text file, so that you can supply a set of localised
  16832. versions of strings that you use in your app.
  16833. To use it in your code, simply call the translate() method on each string that
  16834. might have foreign versions, and if none is found, the method will just return
  16835. the original string.
  16836. The translation file should start with some lines specifying a description of
  16837. the language it contains, and also a list of ISO country codes where it might
  16838. be appropriate to use the file. After that, each line of the file should contain
  16839. a pair of quoted strings with an '=' sign.
  16840. E.g. for a french translation, the file might be:
  16841. @code
  16842. language: French
  16843. countries: fr be mc ch lu
  16844. "hello" = "bonjour"
  16845. "goodbye" = "au revoir"
  16846. @endcode
  16847. If the strings need to contain a quote character, they can use '\"' instead, and
  16848. if the first non-whitespace character on a line isn't a quote, then it's ignored,
  16849. (you can use this to add comments).
  16850. Note that this is a singleton class, so don't create or destroy the object directly.
  16851. There's also a TRANS(text) macro defined to make it easy to use the this.
  16852. E.g. @code
  16853. printSomething (TRANS("hello"));
  16854. @endcode
  16855. This macro is used in the Juce classes themselves, so your application has a chance to
  16856. intercept and translate any internal Juce text strings that might be shown. (You can easily
  16857. get a list of all the messages by searching for the TRANS() macro in the Juce source
  16858. code).
  16859. */
  16860. class JUCE_API LocalisedStrings
  16861. {
  16862. public:
  16863. /** Creates a set of translations from the text of a translation file.
  16864. When you create one of these, you can call setCurrentMappings() to make it
  16865. the set of mappings that the system's using.
  16866. */
  16867. LocalisedStrings (const String& fileContents);
  16868. /** Creates a set of translations from a file.
  16869. When you create one of these, you can call setCurrentMappings() to make it
  16870. the set of mappings that the system's using.
  16871. */
  16872. LocalisedStrings (const File& fileToLoad);
  16873. /** Destructor. */
  16874. ~LocalisedStrings();
  16875. /** Selects the current set of mappings to be used by the system.
  16876. The object you pass in will be automatically deleted when no longer needed, so
  16877. don't keep a pointer to it. You can also pass in zero to remove the current
  16878. mappings.
  16879. See also the TRANS() macro, which uses the current set to do its translation.
  16880. @see translateWithCurrentMappings
  16881. */
  16882. static void setCurrentMappings (LocalisedStrings* newTranslations);
  16883. /** Returns the currently selected set of mappings.
  16884. This is the object that was last passed to setCurrentMappings(). It may
  16885. be 0 if none has been created.
  16886. */
  16887. static LocalisedStrings* getCurrentMappings();
  16888. /** Tries to translate a string using the currently selected set of mappings.
  16889. If no mapping has been set, or if the mapping doesn't contain a translation
  16890. for the string, this will just return the original string.
  16891. See also the TRANS() macro, which uses this method to do its translation.
  16892. @see setCurrentMappings, getCurrentMappings
  16893. */
  16894. static String translateWithCurrentMappings (const String& text);
  16895. /** Tries to translate a string using the currently selected set of mappings.
  16896. If no mapping has been set, or if the mapping doesn't contain a translation
  16897. for the string, this will just return the original string.
  16898. See also the TRANS() macro, which uses this method to do its translation.
  16899. @see setCurrentMappings, getCurrentMappings
  16900. */
  16901. static String translateWithCurrentMappings (const char* text);
  16902. /** Attempts to look up a string and return its localised version.
  16903. If the string isn't found in the list, the original string will be returned.
  16904. */
  16905. String translate (const String& text) const;
  16906. /** Returns the name of the language specified in the translation file.
  16907. This is specified in the file using a line starting with "language:", e.g.
  16908. @code
  16909. language: german
  16910. @endcode
  16911. */
  16912. String getLanguageName() const { return languageName; }
  16913. /** Returns the list of suitable country codes listed in the translation file.
  16914. These is specified in the file using a line starting with "countries:", e.g.
  16915. @code
  16916. countries: fr be mc ch lu
  16917. @endcode
  16918. The country codes are supposed to be 2-character ISO complient codes.
  16919. */
  16920. const StringArray& getCountryCodes() const { return countryCodes; }
  16921. /** Indicates whether to use a case-insensitive search when looking up a string.
  16922. This defaults to true.
  16923. */
  16924. void setIgnoresCase (bool shouldIgnoreCase);
  16925. private:
  16926. String languageName;
  16927. StringArray countryCodes;
  16928. StringPairArray translations;
  16929. void loadFromText (const String& fileContents);
  16930. JUCE_LEAK_DETECTOR (LocalisedStrings);
  16931. };
  16932. #endif // __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  16933. /*** End of inlined file: juce_LocalisedStrings.h ***/
  16934. #endif
  16935. #ifndef __JUCE_NEWLINE_JUCEHEADER__
  16936. #endif
  16937. #ifndef __JUCE_STRING_JUCEHEADER__
  16938. #endif
  16939. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  16940. #endif
  16941. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  16942. #endif
  16943. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  16944. /*** Start of inlined file: juce_StringPool.h ***/
  16945. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  16946. #define __JUCE_STRINGPOOL_JUCEHEADER__
  16947. /**
  16948. A StringPool holds a set of shared strings, which reduces storage overheads and improves
  16949. comparison speed when dealing with many duplicate strings.
  16950. When you add a string to a pool using getPooledString, it'll return a character
  16951. array containing the same string. This array is owned by the pool, and the same array
  16952. is returned every time a matching string is asked for. This means that it's trivial to
  16953. compare two pooled strings for equality, as you can simply compare their pointers. It
  16954. also cuts down on storage if you're using many copies of the same string.
  16955. */
  16956. class JUCE_API StringPool
  16957. {
  16958. public:
  16959. /** Creates an empty pool. */
  16960. StringPool() noexcept;
  16961. /** Destructor */
  16962. ~StringPool();
  16963. /** Returns a pointer to a copy of the string that is passed in.
  16964. The pool will always return the same pointer when asked for a string that matches it.
  16965. The pool will own all the pointers that it returns, deleting them when the pool itself
  16966. is deleted.
  16967. */
  16968. const String::CharPointerType getPooledString (const String& original);
  16969. /** Returns a pointer to a copy of the string that is passed in.
  16970. The pool will always return the same pointer when asked for a string that matches it.
  16971. The pool will own all the pointers that it returns, deleting them when the pool itself
  16972. is deleted.
  16973. */
  16974. const String::CharPointerType getPooledString (const char* original);
  16975. /** Returns a pointer to a copy of the string that is passed in.
  16976. The pool will always return the same pointer when asked for a string that matches it.
  16977. The pool will own all the pointers that it returns, deleting them when the pool itself
  16978. is deleted.
  16979. */
  16980. const String::CharPointerType getPooledString (const wchar_t* original);
  16981. /** Returns the number of strings in the pool. */
  16982. int size() const noexcept;
  16983. /** Returns one of the strings in the pool, by index. */
  16984. const String::CharPointerType operator[] (int index) const noexcept;
  16985. private:
  16986. Array <String> strings;
  16987. };
  16988. #endif // __JUCE_STRINGPOOL_JUCEHEADER__
  16989. /*** End of inlined file: juce_StringPool.h ***/
  16990. #endif
  16991. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  16992. /*** Start of inlined file: juce_XmlDocument.h ***/
  16993. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  16994. #define __JUCE_XMLDOCUMENT_JUCEHEADER__
  16995. class InputSource;
  16996. /**
  16997. Parses a text-based XML document and creates an XmlElement object from it.
  16998. The parser will parse DTDs to load external entities but won't
  16999. check the document for validity against the DTD.
  17000. e.g.
  17001. @code
  17002. XmlDocument myDocument (File ("myfile.xml"));
  17003. XmlElement* mainElement = myDocument.getDocumentElement();
  17004. if (mainElement == nullptr)
  17005. {
  17006. String error = myDocument.getLastParseError();
  17007. }
  17008. else
  17009. {
  17010. ..use the element
  17011. }
  17012. @endcode
  17013. Or you can use the static helper methods for quick parsing..
  17014. @code
  17015. XmlElement* xml = XmlDocument::parse (myXmlFile);
  17016. if (xml != nullptr && xml->hasTagName ("foobar"))
  17017. {
  17018. ...etc
  17019. @endcode
  17020. @see XmlElement
  17021. */
  17022. class JUCE_API XmlDocument
  17023. {
  17024. public:
  17025. /** Creates an XmlDocument from the xml text.
  17026. The text doesn't actually get parsed until the getDocumentElement() method is called.
  17027. */
  17028. XmlDocument (const String& documentText);
  17029. /** Creates an XmlDocument from a file.
  17030. The text doesn't actually get parsed until the getDocumentElement() method is called.
  17031. */
  17032. XmlDocument (const File& file);
  17033. /** Destructor. */
  17034. ~XmlDocument();
  17035. /** Creates an XmlElement object to represent the main document node.
  17036. This method will do the actual parsing of the text, and if there's a
  17037. parse error, it may returns 0 (and you can find out the error using
  17038. the getLastParseError() method).
  17039. See also the parse() methods, which provide a shorthand way to quickly
  17040. parse a file or string.
  17041. @param onlyReadOuterDocumentElement if true, the parser will only read the
  17042. first section of the file, and will only
  17043. return the outer document element - this
  17044. allows quick checking of large files to
  17045. see if they contain the correct type of
  17046. tag, without having to parse the entire file
  17047. @returns a new XmlElement which the caller will need to delete, or null if
  17048. there was an error.
  17049. @see getLastParseError
  17050. */
  17051. XmlElement* getDocumentElement (bool onlyReadOuterDocumentElement = false);
  17052. /** Returns the parsing error that occurred the last time getDocumentElement was called.
  17053. @returns the error, or an empty string if there was no error.
  17054. */
  17055. const String& getLastParseError() const noexcept;
  17056. /** Sets an input source object to use for parsing documents that reference external entities.
  17057. If the document has been created from a file, this probably won't be needed, but
  17058. if you're parsing some text and there might be a DTD that references external
  17059. files, you may need to create a custom input source that can retrieve the
  17060. other files it needs.
  17061. The object that is passed-in will be deleted automatically when no longer needed.
  17062. @see InputSource
  17063. */
  17064. void setInputSource (InputSource* newSource) noexcept;
  17065. /** Sets a flag to change the treatment of empty text elements.
  17066. If this is true (the default state), then any text elements that contain only
  17067. whitespace characters will be ingored during parsing. If you need to catch
  17068. whitespace-only text, then you should set this to false before calling the
  17069. getDocumentElement() method.
  17070. */
  17071. void setEmptyTextElementsIgnored (bool shouldBeIgnored) noexcept;
  17072. /** A handy static method that parses a file.
  17073. This is a shortcut for creating an XmlDocument object and calling getDocumentElement() on it.
  17074. @returns a new XmlElement which the caller will need to delete, or null if there was an error.
  17075. */
  17076. static XmlElement* parse (const File& file);
  17077. /** A handy static method that parses some XML data.
  17078. This is a shortcut for creating an XmlDocument object and calling getDocumentElement() on it.
  17079. @returns a new XmlElement which the caller will need to delete, or null if there was an error.
  17080. */
  17081. static XmlElement* parse (const String& xmlData);
  17082. private:
  17083. String originalText;
  17084. String::CharPointerType input;
  17085. bool outOfData, errorOccurred;
  17086. String lastError, dtdText;
  17087. StringArray tokenisedDTD;
  17088. bool needToLoadDTD, ignoreEmptyTextElements;
  17089. ScopedPointer <InputSource> inputSource;
  17090. void setLastError (const String& desc, bool carryOn);
  17091. void skipHeader();
  17092. void skipNextWhiteSpace();
  17093. juce_wchar readNextChar() noexcept;
  17094. XmlElement* readNextElement (bool alsoParseSubElements);
  17095. void readChildElements (XmlElement* parent);
  17096. int findNextTokenLength() noexcept;
  17097. void readQuotedString (String& result);
  17098. void readEntity (String& result);
  17099. String getFileContents (const String& filename) const;
  17100. String expandEntity (const String& entity);
  17101. String expandExternalEntity (const String& entity);
  17102. String getParameterEntity (const String& entity);
  17103. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XmlDocument);
  17104. };
  17105. #endif // __JUCE_XMLDOCUMENT_JUCEHEADER__
  17106. /*** End of inlined file: juce_XmlDocument.h ***/
  17107. #endif
  17108. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  17109. #endif
  17110. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  17111. #endif
  17112. #ifndef __JUCE_DYNAMICLIBRARY_JUCEHEADER__
  17113. /*** Start of inlined file: juce_DynamicLibrary.h ***/
  17114. #ifndef __JUCE_DYNAMICLIBRARY_JUCEHEADER__
  17115. #define __JUCE_DYNAMICLIBRARY_JUCEHEADER__
  17116. /**
  17117. Handles the opening and closing of DLLs.
  17118. This class can be used to open a DLL and get some function pointers from it.
  17119. Since the DLL is freed when this object is deleted, it's handy for managing
  17120. library lifetimes using RAII.
  17121. */
  17122. class DynamicLibrary
  17123. {
  17124. public:
  17125. /** Creates an unopened DynamicLibrary object.
  17126. Call open() to actually open one.
  17127. */
  17128. DynamicLibrary() noexcept : handle (nullptr) {}
  17129. /**
  17130. */
  17131. DynamicLibrary (const String& name) : handle (nullptr) { open (name); }
  17132. /** Destructor.
  17133. If a library is currently open, it will be closed when this object is destroyed.
  17134. */
  17135. ~DynamicLibrary() { close(); }
  17136. /** Opens a DLL.
  17137. The name and the method by which it gets found is of course platform-specific, and
  17138. may or may not include a path, depending on the OS.
  17139. If a library is already open when this method is called, it will first close the library
  17140. before attempting to load the new one.
  17141. @returns true if the library was successfully found and opened.
  17142. */
  17143. bool open (const String& name);
  17144. /** Releases the currently-open DLL, or has no effect if none was open. */
  17145. void close() noexcept;
  17146. /** Tries to find a named function in the currently-open DLL, and returns a pointer to it.
  17147. If no library is open, or if the function isn't found, this will return a null pointer.
  17148. */
  17149. void* getFunction (const String& functionName) noexcept;
  17150. /** Returns the platform-specific native library handle.
  17151. You'll need to cast this to whatever is appropriate for the OS that's in use.
  17152. */
  17153. void* getNativeHandle() const noexcept { return handle; }
  17154. private:
  17155. void* handle;
  17156. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DynamicLibrary);
  17157. };
  17158. #endif // __JUCE_DYNAMICLIBRARY_JUCEHEADER__
  17159. /*** End of inlined file: juce_DynamicLibrary.h ***/
  17160. #endif
  17161. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  17162. /*** Start of inlined file: juce_InterProcessLock.h ***/
  17163. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  17164. #define __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  17165. /**
  17166. Acts as a critical section which processes can use to block each other.
  17167. @see CriticalSection
  17168. */
  17169. class JUCE_API InterProcessLock
  17170. {
  17171. public:
  17172. /** Creates a lock object.
  17173. @param name a name that processes will use to identify this lock object
  17174. */
  17175. explicit InterProcessLock (const String& name);
  17176. /** Destructor.
  17177. This will also release the lock if it's currently held by this process.
  17178. */
  17179. ~InterProcessLock();
  17180. /** Attempts to lock the critical section.
  17181. @param timeOutMillisecs how many milliseconds to wait if the lock
  17182. is already held by another process - a value of
  17183. 0 will return immediately, negative values will wait
  17184. forever
  17185. @returns true if the lock could be gained within the timeout period, or
  17186. false if the timeout expired.
  17187. */
  17188. bool enter (int timeOutMillisecs = -1);
  17189. /** Releases the lock if it's currently held by this process.
  17190. */
  17191. void exit();
  17192. /**
  17193. Automatically locks and unlocks an InterProcessLock object.
  17194. This works like a ScopedLock, but using an InterprocessLock rather than
  17195. a CriticalSection.
  17196. @see ScopedLock
  17197. */
  17198. class ScopedLockType
  17199. {
  17200. public:
  17201. /** Creates a scoped lock.
  17202. As soon as it is created, this will lock the InterProcessLock, and
  17203. when the ScopedLockType object is deleted, the InterProcessLock will
  17204. be unlocked.
  17205. Note that since an InterprocessLock can fail due to errors, you should check
  17206. isLocked() to make sure that the lock was successful before using it.
  17207. Make sure this object is created and deleted by the same thread,
  17208. otherwise there are no guarantees what will happen! Best just to use it
  17209. as a local stack object, rather than creating one with the new() operator.
  17210. */
  17211. explicit ScopedLockType (InterProcessLock& lock) : lock_ (lock) { lockWasSuccessful = lock.enter(); }
  17212. /** Destructor.
  17213. The InterProcessLock will be unlocked when the destructor is called.
  17214. Make sure this object is created and deleted by the same thread,
  17215. otherwise there are no guarantees what will happen!
  17216. */
  17217. inline ~ScopedLockType() { lock_.exit(); }
  17218. /** Returns true if the InterProcessLock was successfully locked. */
  17219. bool isLocked() const noexcept { return lockWasSuccessful; }
  17220. private:
  17221. InterProcessLock& lock_;
  17222. bool lockWasSuccessful;
  17223. JUCE_DECLARE_NON_COPYABLE (ScopedLockType);
  17224. };
  17225. private:
  17226. class Pimpl;
  17227. friend class ScopedPointer <Pimpl>;
  17228. ScopedPointer <Pimpl> pimpl;
  17229. CriticalSection lock;
  17230. String name;
  17231. JUCE_DECLARE_NON_COPYABLE (InterProcessLock);
  17232. };
  17233. #endif // __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  17234. /*** End of inlined file: juce_InterProcessLock.h ***/
  17235. #endif
  17236. #ifndef __JUCE_PROCESS_JUCEHEADER__
  17237. /*** Start of inlined file: juce_Process.h ***/
  17238. #ifndef __JUCE_PROCESS_JUCEHEADER__
  17239. #define __JUCE_PROCESS_JUCEHEADER__
  17240. /** Represents the current executable's process.
  17241. This contains methods for controlling the current application at the
  17242. process-level.
  17243. @see Thread, JUCEApplication
  17244. */
  17245. class JUCE_API Process
  17246. {
  17247. public:
  17248. enum ProcessPriority
  17249. {
  17250. LowPriority = 0,
  17251. NormalPriority = 1,
  17252. HighPriority = 2,
  17253. RealtimePriority = 3
  17254. };
  17255. /** Changes the current process's priority.
  17256. @param priority the process priority, where
  17257. 0=low, 1=normal, 2=high, 3=realtime
  17258. */
  17259. static void setPriority (const ProcessPriority priority);
  17260. /** Kills the current process immediately.
  17261. This is an emergency process terminator that kills the application
  17262. immediately - it's intended only for use only when something goes
  17263. horribly wrong.
  17264. @see JUCEApplication::quit
  17265. */
  17266. static void terminate();
  17267. /** Returns true if this application process is the one that the user is
  17268. currently using.
  17269. */
  17270. static bool isForegroundProcess();
  17271. /** Raises the current process's privilege level.
  17272. Does nothing if this isn't supported by the current OS, or if process
  17273. privilege level is fixed.
  17274. */
  17275. static void raisePrivilege();
  17276. /** Lowers the current process's privilege level.
  17277. Does nothing if this isn't supported by the current OS, or if process
  17278. privilege level is fixed.
  17279. */
  17280. static void lowerPrivilege();
  17281. /** Returns true if this process is being hosted by a debugger.
  17282. */
  17283. static bool JUCE_CALLTYPE isRunningUnderDebugger();
  17284. /** Tries to launch the OS's default reader application for a given file or URL. */
  17285. static bool openDocument (const String& documentURL, const String& parameters);
  17286. /** Tries to launch the OS's default email application to let the user create a message. */
  17287. static bool openEmailWithAttachments (const String& targetEmailAddress,
  17288. const String& emailSubject,
  17289. const String& bodyText,
  17290. const StringArray& filesToAttach);
  17291. #if JUCE_WINDOWS || DOXYGEN
  17292. /** WINDOWS ONLY - This returns the HINSTANCE of the current module.
  17293. The return type is a void* to avoid being dependent on windows.h - just cast
  17294. it to a HINSTANCE to use it.
  17295. In a normal JUCE application, this will be automatically set to the module
  17296. handle of the executable.
  17297. If you've built a DLL and plan to use any JUCE messaging or windowing classes,
  17298. you'll need to make sure you call the setCurrentModuleInstanceHandle()
  17299. to provide the correct module handle in your DllMain() function, because
  17300. the system relies on the correct instance handle when opening windows.
  17301. */
  17302. static void* JUCE_CALLTYPE getCurrentModuleInstanceHandle() noexcept;
  17303. /** WINDOWS ONLY - Sets a new module handle to be used by the library.
  17304. The parameter type is a void* to avoid being dependent on windows.h, but it actually
  17305. expects a HINSTANCE value.
  17306. @see getCurrentModuleInstanceHandle()
  17307. */
  17308. static void JUCE_CALLTYPE setCurrentModuleInstanceHandle (void* newHandle) noexcept;
  17309. /** WINDOWS ONLY - Gets the command-line params as a string.
  17310. This is needed to avoid unicode problems with the argc type params.
  17311. */
  17312. static String JUCE_CALLTYPE getCurrentCommandLineParams();
  17313. #endif
  17314. private:
  17315. Process();
  17316. JUCE_DECLARE_NON_COPYABLE (Process);
  17317. };
  17318. #endif // __JUCE_PROCESS_JUCEHEADER__
  17319. /*** End of inlined file: juce_Process.h ***/
  17320. #endif
  17321. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  17322. /*** Start of inlined file: juce_ReadWriteLock.h ***/
  17323. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  17324. #define __JUCE_READWRITELOCK_JUCEHEADER__
  17325. /*** Start of inlined file: juce_SpinLock.h ***/
  17326. #ifndef __JUCE_SPINLOCK_JUCEHEADER__
  17327. #define __JUCE_SPINLOCK_JUCEHEADER__
  17328. /**
  17329. A simple spin-lock class that can be used as a simple, low-overhead mutex for
  17330. uncontended situations.
  17331. Note that unlike a CriticalSection, this type of lock is not re-entrant, and may
  17332. be less efficient when used it a highly contended situation, but it's very small and
  17333. requires almost no initialisation.
  17334. It's most appropriate for simple situations where you're only going to hold the
  17335. lock for a very brief time.
  17336. @see CriticalSection
  17337. */
  17338. class JUCE_API SpinLock
  17339. {
  17340. public:
  17341. inline SpinLock() noexcept {}
  17342. inline ~SpinLock() noexcept {}
  17343. /** Acquires the lock.
  17344. This will block until the lock has been successfully acquired by this thread.
  17345. Note that a SpinLock is NOT re-entrant, and is not smart enough to know whether the
  17346. caller thread already has the lock - so if a thread tries to acquire a lock that it
  17347. already holds, this method will never return!
  17348. It's strongly recommended that you never call this method directly - instead use the
  17349. ScopedLockType class to manage the locking using an RAII pattern instead.
  17350. */
  17351. void enter() const noexcept;
  17352. /** Attempts to acquire the lock, returning true if this was successful. */
  17353. inline bool tryEnter() const noexcept
  17354. {
  17355. return lock.compareAndSetBool (1, 0);
  17356. }
  17357. /** Releases the lock. */
  17358. inline void exit() const noexcept
  17359. {
  17360. jassert (lock.value == 1); // Agh! Releasing a lock that isn't currently held!
  17361. lock = 0;
  17362. }
  17363. /** Provides the type of scoped lock to use for locking a SpinLock. */
  17364. typedef GenericScopedLock <SpinLock> ScopedLockType;
  17365. /** Provides the type of scoped unlocker to use with a SpinLock. */
  17366. typedef GenericScopedUnlock <SpinLock> ScopedUnlockType;
  17367. private:
  17368. mutable Atomic<int> lock;
  17369. JUCE_DECLARE_NON_COPYABLE (SpinLock);
  17370. };
  17371. #endif // __JUCE_SPINLOCK_JUCEHEADER__
  17372. /*** End of inlined file: juce_SpinLock.h ***/
  17373. /*** Start of inlined file: juce_WaitableEvent.h ***/
  17374. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  17375. #define __JUCE_WAITABLEEVENT_JUCEHEADER__
  17376. /**
  17377. Allows threads to wait for events triggered by other threads.
  17378. A thread can call wait() on a WaitableObject, and this will suspend the
  17379. calling thread until another thread wakes it up by calling the signal()
  17380. method.
  17381. */
  17382. class JUCE_API WaitableEvent
  17383. {
  17384. public:
  17385. /** Creates a WaitableEvent object.
  17386. @param manualReset If this is false, the event will be reset automatically when the wait()
  17387. method is called. If manualReset is true, then once the event is signalled,
  17388. the only way to reset it will be by calling the reset() method.
  17389. */
  17390. WaitableEvent (bool manualReset = false) noexcept;
  17391. /** Destructor.
  17392. If other threads are waiting on this object when it gets deleted, this
  17393. can cause nasty errors, so be careful!
  17394. */
  17395. ~WaitableEvent() noexcept;
  17396. /** Suspends the calling thread until the event has been signalled.
  17397. This will wait until the object's signal() method is called by another thread,
  17398. or until the timeout expires.
  17399. After the event has been signalled, this method will return true and if manualReset
  17400. was set to false in the WaitableEvent's constructor, then the event will be reset.
  17401. @param timeOutMilliseconds the maximum time to wait, in milliseconds. A negative
  17402. value will cause it to wait forever.
  17403. @returns true if the object has been signalled, false if the timeout expires first.
  17404. @see signal, reset
  17405. */
  17406. bool wait (int timeOutMilliseconds = -1) const noexcept;
  17407. /** Wakes up any threads that are currently waiting on this object.
  17408. If signal() is called when nothing is waiting, the next thread to call wait()
  17409. will return immediately and reset the signal.
  17410. If the WaitableEvent is manual reset, all current and future threads that wait upon this
  17411. object will be woken, until reset() is explicitly called.
  17412. If the WaitableEvent is automatic reset, and one or more threads is waiting upon the object,
  17413. then one of them will be woken up. If no threads are currently waiting, then the next thread
  17414. to call wait() will be woken up. As soon as a thread is woken, the signal is automatically
  17415. reset.
  17416. @see wait, reset
  17417. */
  17418. void signal() const noexcept;
  17419. /** Resets the event to an unsignalled state.
  17420. If it's not already signalled, this does nothing.
  17421. */
  17422. void reset() const noexcept;
  17423. private:
  17424. void* internal;
  17425. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WaitableEvent);
  17426. };
  17427. #endif // __JUCE_WAITABLEEVENT_JUCEHEADER__
  17428. /*** End of inlined file: juce_WaitableEvent.h ***/
  17429. /*** Start of inlined file: juce_Thread.h ***/
  17430. #ifndef __JUCE_THREAD_JUCEHEADER__
  17431. #define __JUCE_THREAD_JUCEHEADER__
  17432. /**
  17433. Encapsulates a thread.
  17434. Subclasses derive from Thread and implement the run() method, in which they
  17435. do their business. The thread can then be started with the startThread() method
  17436. and controlled with various other methods.
  17437. This class also contains some thread-related static methods, such
  17438. as sleep(), yield(), getCurrentThreadId() etc.
  17439. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  17440. MessageManagerLock
  17441. */
  17442. class JUCE_API Thread
  17443. {
  17444. public:
  17445. /**
  17446. Creates a thread.
  17447. When first created, the thread is not running. Use the startThread()
  17448. method to start it.
  17449. */
  17450. explicit Thread (const String& threadName);
  17451. /** Destructor.
  17452. Deleting a Thread object that is running will only give the thread a
  17453. brief opportunity to stop itself cleanly, so it's recommended that you
  17454. should always call stopThread() with a decent timeout before deleting,
  17455. to avoid the thread being forcibly killed (which is a Bad Thing).
  17456. */
  17457. virtual ~Thread();
  17458. /** Must be implemented to perform the thread's actual code.
  17459. Remember that the thread must regularly check the threadShouldExit()
  17460. method whilst running, and if this returns true it should return from
  17461. the run() method as soon as possible to avoid being forcibly killed.
  17462. @see threadShouldExit, startThread
  17463. */
  17464. virtual void run() = 0;
  17465. // Thread control functions..
  17466. /** Starts the thread running.
  17467. This will start the thread's run() method.
  17468. (if it's already started, startThread() won't do anything).
  17469. @see stopThread
  17470. */
  17471. void startThread();
  17472. /** Starts the thread with a given priority.
  17473. Launches the thread with a given priority, where 0 = lowest, 10 = highest.
  17474. If the thread is already running, its priority will be changed.
  17475. @see startThread, setPriority
  17476. */
  17477. void startThread (int priority);
  17478. /** Attempts to stop the thread running.
  17479. This method will cause the threadShouldExit() method to return true
  17480. and call notify() in case the thread is currently waiting.
  17481. Hopefully the thread will then respond to this by exiting cleanly, and
  17482. the stopThread method will wait for a given time-period for this to
  17483. happen.
  17484. If the thread is stuck and fails to respond after the time-out, it gets
  17485. forcibly killed, which is a very bad thing to happen, as it could still
  17486. be holding locks, etc. which are needed by other parts of your program.
  17487. @param timeOutMilliseconds The number of milliseconds to wait for the
  17488. thread to finish before killing it by force. A negative
  17489. value in here will wait forever.
  17490. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  17491. */
  17492. void stopThread (int timeOutMilliseconds);
  17493. /** Returns true if the thread is currently active */
  17494. bool isThreadRunning() const;
  17495. /** Sets a flag to tell the thread it should stop.
  17496. Calling this means that the threadShouldExit() method will then return true.
  17497. The thread should be regularly checking this to see whether it should exit.
  17498. If your thread makes use of wait(), you might want to call notify() after calling
  17499. this method, to interrupt any waits that might be in progress, and allow it
  17500. to reach a point where it can exit.
  17501. @see threadShouldExit
  17502. @see waitForThreadToExit
  17503. */
  17504. void signalThreadShouldExit();
  17505. /** Checks whether the thread has been told to stop running.
  17506. Threads need to check this regularly, and if it returns true, they should
  17507. return from their run() method at the first possible opportunity.
  17508. @see signalThreadShouldExit
  17509. */
  17510. inline bool threadShouldExit() const { return threadShouldExit_; }
  17511. /** Waits for the thread to stop.
  17512. This will waits until isThreadRunning() is false or until a timeout expires.
  17513. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  17514. is less than zero, it will wait forever.
  17515. @returns true if the thread exits, or false if the timeout expires first.
  17516. */
  17517. bool waitForThreadToExit (int timeOutMilliseconds) const;
  17518. /** Changes the thread's priority.
  17519. May return false if for some reason the priority can't be changed.
  17520. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  17521. of 5 is normal.
  17522. */
  17523. bool setPriority (int priority);
  17524. /** Changes the priority of the caller thread.
  17525. Similar to setPriority(), but this static method acts on the caller thread.
  17526. May return false if for some reason the priority can't be changed.
  17527. @see setPriority
  17528. */
  17529. static bool setCurrentThreadPriority (int priority);
  17530. /** Sets the affinity mask for the thread.
  17531. This will only have an effect next time the thread is started - i.e. if the
  17532. thread is already running when called, it'll have no effect.
  17533. @see setCurrentThreadAffinityMask
  17534. */
  17535. void setAffinityMask (uint32 affinityMask);
  17536. /** Changes the affinity mask for the caller thread.
  17537. This will change the affinity mask for the thread that calls this static method.
  17538. @see setAffinityMask
  17539. */
  17540. static void setCurrentThreadAffinityMask (uint32 affinityMask);
  17541. // this can be called from any thread that needs to pause..
  17542. static void JUCE_CALLTYPE sleep (int milliseconds);
  17543. /** Yields the calling thread's current time-slot. */
  17544. static void JUCE_CALLTYPE yield();
  17545. /** Makes the thread wait for a notification.
  17546. This puts the thread to sleep until either the timeout period expires, or
  17547. another thread calls the notify() method to wake it up.
  17548. A negative time-out value means that the method will wait indefinitely.
  17549. @returns true if the event has been signalled, false if the timeout expires.
  17550. */
  17551. bool wait (int timeOutMilliseconds) const;
  17552. /** Wakes up the thread.
  17553. If the thread has called the wait() method, this will wake it up.
  17554. @see wait
  17555. */
  17556. void notify() const;
  17557. /** A value type used for thread IDs.
  17558. @see getCurrentThreadId(), getThreadId()
  17559. */
  17560. typedef void* ThreadID;
  17561. /** Returns an id that identifies the caller thread.
  17562. To find the ID of a particular thread object, use getThreadId().
  17563. @returns a unique identifier that identifies the calling thread.
  17564. @see getThreadId
  17565. */
  17566. static ThreadID getCurrentThreadId();
  17567. /** Finds the thread object that is currently running.
  17568. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  17569. object associated with them, so this will return 0.
  17570. */
  17571. static Thread* getCurrentThread();
  17572. /** Returns the ID of this thread.
  17573. That means the ID of this thread object - not of the thread that's calling the method.
  17574. This can change when the thread is started and stopped, and will be invalid if the
  17575. thread's not actually running.
  17576. @see getCurrentThreadId
  17577. */
  17578. ThreadID getThreadId() const noexcept { return threadId_; }
  17579. /** Returns the name of the thread.
  17580. This is the name that gets set in the constructor.
  17581. */
  17582. const String& getThreadName() const { return threadName_; }
  17583. /** Changes the name of the caller thread.
  17584. Different OSes may place different length or content limits on this name.
  17585. */
  17586. static void setCurrentThreadName (const String& newThreadName);
  17587. /** Returns the number of currently-running threads.
  17588. @returns the number of Thread objects known to be currently running.
  17589. @see stopAllThreads
  17590. */
  17591. static int getNumRunningThreads();
  17592. /** Tries to stop all currently-running threads.
  17593. This will attempt to stop all the threads known to be running at the moment.
  17594. */
  17595. static void stopAllThreads (int timeoutInMillisecs);
  17596. private:
  17597. const String threadName_;
  17598. void* volatile threadHandle_;
  17599. ThreadID threadId_;
  17600. CriticalSection startStopLock;
  17601. WaitableEvent startSuspensionEvent_, defaultEvent_;
  17602. int threadPriority_;
  17603. uint32 affinityMask_;
  17604. bool volatile threadShouldExit_;
  17605. #ifndef DOXYGEN
  17606. friend class MessageManager;
  17607. friend void JUCE_API juce_threadEntryPoint (void*);
  17608. #endif
  17609. void launchThread();
  17610. void closeThreadHandle();
  17611. void killThread();
  17612. void threadEntryPoint();
  17613. static bool setThreadPriority (void* handle, int priority);
  17614. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Thread);
  17615. };
  17616. #endif // __JUCE_THREAD_JUCEHEADER__
  17617. /*** End of inlined file: juce_Thread.h ***/
  17618. /**
  17619. A critical section that allows multiple simultaneous readers.
  17620. Features of this type of lock are:
  17621. - Multiple readers can hold the lock at the same time, but only one writer
  17622. can hold it at once.
  17623. - Writers trying to gain the lock will be blocked until all readers and writers
  17624. have released it
  17625. - Readers trying to gain the lock while a writer is waiting to acquire it will be
  17626. blocked until the writer has obtained and released it
  17627. - If a thread already has a read lock and tries to obtain a write lock, it will succeed if
  17628. there are no other readers
  17629. - If a thread already has the write lock and tries to obtain a read lock, this will succeed.
  17630. - Recursive locking is supported.
  17631. @see ScopedReadLock, ScopedWriteLock, CriticalSection
  17632. */
  17633. class JUCE_API ReadWriteLock
  17634. {
  17635. public:
  17636. /**
  17637. Creates a ReadWriteLock object.
  17638. */
  17639. ReadWriteLock() noexcept;
  17640. /** Destructor.
  17641. If the object is deleted whilst locked, any subsequent behaviour
  17642. is unpredictable.
  17643. */
  17644. ~ReadWriteLock() noexcept;
  17645. /** Locks this object for reading.
  17646. Multiple threads can simulaneously lock the object for reading, but if another
  17647. thread has it locked for writing, then this will block until it releases the
  17648. lock.
  17649. @see exitRead, ScopedReadLock
  17650. */
  17651. void enterRead() const noexcept;
  17652. /** Releases the read-lock.
  17653. If the caller thread hasn't got the lock, this can have unpredictable results.
  17654. If the enterRead() method has been called multiple times by the thread, each
  17655. call must be matched by a call to exitRead() before other threads will be allowed
  17656. to take over the lock.
  17657. @see enterRead, ScopedReadLock
  17658. */
  17659. void exitRead() const noexcept;
  17660. /** Locks this object for writing.
  17661. This will block until any other threads that have it locked for reading or
  17662. writing have released their lock.
  17663. @see exitWrite, ScopedWriteLock
  17664. */
  17665. void enterWrite() const noexcept;
  17666. /** Tries to lock this object for writing.
  17667. This is like enterWrite(), but doesn't block - it returns true if it manages
  17668. to obtain the lock.
  17669. @see enterWrite
  17670. */
  17671. bool tryEnterWrite() const noexcept;
  17672. /** Releases the write-lock.
  17673. If the caller thread hasn't got the lock, this can have unpredictable results.
  17674. If the enterWrite() method has been called multiple times by the thread, each
  17675. call must be matched by a call to exit() before other threads will be allowed
  17676. to take over the lock.
  17677. @see enterWrite, ScopedWriteLock
  17678. */
  17679. void exitWrite() const noexcept;
  17680. private:
  17681. SpinLock accessLock;
  17682. WaitableEvent waitEvent;
  17683. mutable int numWaitingWriters, numWriters;
  17684. mutable Thread::ThreadID writerThreadId;
  17685. mutable Array <Thread::ThreadID> readerThreads;
  17686. JUCE_DECLARE_NON_COPYABLE (ReadWriteLock);
  17687. };
  17688. #endif // __JUCE_READWRITELOCK_JUCEHEADER__
  17689. /*** End of inlined file: juce_ReadWriteLock.h ***/
  17690. #endif
  17691. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  17692. #endif
  17693. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  17694. /*** Start of inlined file: juce_ScopedReadLock.h ***/
  17695. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  17696. #define __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  17697. /**
  17698. Automatically locks and unlocks a ReadWriteLock object.
  17699. Use one of these as a local variable to control access to a ReadWriteLock.
  17700. e.g. @code
  17701. ReadWriteLock myLock;
  17702. for (;;)
  17703. {
  17704. const ScopedReadLock myScopedLock (myLock);
  17705. // myLock is now locked
  17706. ...do some stuff...
  17707. // myLock gets unlocked here.
  17708. }
  17709. @endcode
  17710. @see ReadWriteLock, ScopedWriteLock
  17711. */
  17712. class JUCE_API ScopedReadLock
  17713. {
  17714. public:
  17715. /** Creates a ScopedReadLock.
  17716. As soon as it is created, this will call ReadWriteLock::enterRead(), and
  17717. when the ScopedReadLock object is deleted, the ReadWriteLock will
  17718. be unlocked.
  17719. Make sure this object is created and deleted by the same thread,
  17720. otherwise there are no guarantees what will happen! Best just to use it
  17721. as a local stack object, rather than creating one with the new() operator.
  17722. */
  17723. inline explicit ScopedReadLock (const ReadWriteLock& lock) noexcept : lock_ (lock) { lock.enterRead(); }
  17724. /** Destructor.
  17725. The ReadWriteLock's exitRead() method will be called when the destructor is called.
  17726. Make sure this object is created and deleted by the same thread,
  17727. otherwise there are no guarantees what will happen!
  17728. */
  17729. inline ~ScopedReadLock() noexcept { lock_.exitRead(); }
  17730. private:
  17731. const ReadWriteLock& lock_;
  17732. JUCE_DECLARE_NON_COPYABLE (ScopedReadLock);
  17733. };
  17734. #endif // __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  17735. /*** End of inlined file: juce_ScopedReadLock.h ***/
  17736. #endif
  17737. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  17738. /*** Start of inlined file: juce_ScopedWriteLock.h ***/
  17739. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  17740. #define __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  17741. /**
  17742. Automatically locks and unlocks a ReadWriteLock object.
  17743. Use one of these as a local variable to control access to a ReadWriteLock.
  17744. e.g. @code
  17745. ReadWriteLock myLock;
  17746. for (;;)
  17747. {
  17748. const ScopedWriteLock myScopedLock (myLock);
  17749. // myLock is now locked
  17750. ...do some stuff...
  17751. // myLock gets unlocked here.
  17752. }
  17753. @endcode
  17754. @see ReadWriteLock, ScopedReadLock
  17755. */
  17756. class JUCE_API ScopedWriteLock
  17757. {
  17758. public:
  17759. /** Creates a ScopedWriteLock.
  17760. As soon as it is created, this will call ReadWriteLock::enterWrite(), and
  17761. when the ScopedWriteLock object is deleted, the ReadWriteLock will
  17762. be unlocked.
  17763. Make sure this object is created and deleted by the same thread,
  17764. otherwise there are no guarantees what will happen! Best just to use it
  17765. as a local stack object, rather than creating one with the new() operator.
  17766. */
  17767. inline explicit ScopedWriteLock (const ReadWriteLock& lock) noexcept : lock_ (lock) { lock.enterWrite(); }
  17768. /** Destructor.
  17769. The ReadWriteLock's exitWrite() method will be called when the destructor is called.
  17770. Make sure this object is created and deleted by the same thread,
  17771. otherwise there are no guarantees what will happen!
  17772. */
  17773. inline ~ScopedWriteLock() noexcept { lock_.exitWrite(); }
  17774. private:
  17775. const ReadWriteLock& lock_;
  17776. JUCE_DECLARE_NON_COPYABLE (ScopedWriteLock);
  17777. };
  17778. #endif // __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  17779. /*** End of inlined file: juce_ScopedWriteLock.h ***/
  17780. #endif
  17781. #ifndef __JUCE_SPINLOCK_JUCEHEADER__
  17782. #endif
  17783. #ifndef __JUCE_THREAD_JUCEHEADER__
  17784. #endif
  17785. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  17786. /*** Start of inlined file: juce_ThreadPool.h ***/
  17787. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  17788. #define __JUCE_THREADPOOL_JUCEHEADER__
  17789. class ThreadPool;
  17790. class ThreadPoolThread;
  17791. /**
  17792. A task that is executed by a ThreadPool object.
  17793. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  17794. its threads.
  17795. The runJob() method needs to be implemented to do the task, and if the code that
  17796. does the work takes a significant time to run, it must keep checking the shouldExit()
  17797. method to see if something is trying to interrupt the job. If shouldExit() returns
  17798. true, the runJob() method must return immediately.
  17799. @see ThreadPool, Thread
  17800. */
  17801. class JUCE_API ThreadPoolJob
  17802. {
  17803. public:
  17804. /** Creates a thread pool job object.
  17805. After creating your job, add it to a thread pool with ThreadPool::addJob().
  17806. */
  17807. explicit ThreadPoolJob (const String& name);
  17808. /** Destructor. */
  17809. virtual ~ThreadPoolJob();
  17810. /** Returns the name of this job.
  17811. @see setJobName
  17812. */
  17813. String getJobName() const;
  17814. /** Changes the job's name.
  17815. @see getJobName
  17816. */
  17817. void setJobName (const String& newName);
  17818. /** These are the values that can be returned by the runJob() method.
  17819. */
  17820. enum JobStatus
  17821. {
  17822. jobHasFinished = 0, /**< indicates that the job has finished and can be
  17823. removed from the pool. */
  17824. jobHasFinishedAndShouldBeDeleted, /**< indicates that the job has finished and that it
  17825. should be automatically deleted by the pool. */
  17826. jobNeedsRunningAgain /**< indicates that the job would like to be called
  17827. again when a thread is free. */
  17828. };
  17829. /** Peforms the actual work that this job needs to do.
  17830. Your subclass must implement this method, in which is does its work.
  17831. If the code in this method takes a significant time to run, it must repeatedly check
  17832. the shouldExit() method to see if something is trying to interrupt the job.
  17833. If shouldExit() ever returns true, the runJob() method must return immediately.
  17834. If this method returns jobHasFinished, then the job will be removed from the pool
  17835. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  17836. pool and will get a chance to run again as soon as a thread is free.
  17837. @see shouldExit()
  17838. */
  17839. virtual JobStatus runJob() = 0;
  17840. /** Returns true if this job is currently running its runJob() method. */
  17841. bool isRunning() const { return isActive; }
  17842. /** Returns true if something is trying to interrupt this job and make it stop.
  17843. Your runJob() method must call this whenever it gets a chance, and if it ever
  17844. returns true, the runJob() method must return immediately.
  17845. @see signalJobShouldExit()
  17846. */
  17847. bool shouldExit() const { return shouldStop; }
  17848. /** Calling this will cause the shouldExit() method to return true, and the job
  17849. should (if it's been implemented correctly) stop as soon as possible.
  17850. @see shouldExit()
  17851. */
  17852. void signalJobShouldExit();
  17853. private:
  17854. friend class ThreadPool;
  17855. friend class ThreadPoolThread;
  17856. String jobName;
  17857. ThreadPool* pool;
  17858. bool shouldStop, isActive, shouldBeDeleted;
  17859. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolJob);
  17860. };
  17861. /**
  17862. A set of threads that will run a list of jobs.
  17863. When a ThreadPoolJob object is added to the ThreadPool's list, its run() method
  17864. will be called by the next pooled thread that becomes free.
  17865. @see ThreadPoolJob, Thread
  17866. */
  17867. class JUCE_API ThreadPool
  17868. {
  17869. public:
  17870. /** Creates a thread pool.
  17871. Once you've created a pool, you can give it some things to do with the addJob()
  17872. method.
  17873. @param numberOfThreads the maximum number of actual threads to run.
  17874. @param startThreadsOnlyWhenNeeded if this is true, then no threads will be started
  17875. until there are some jobs to run. If false, then
  17876. all the threads will be fired-up immediately so that
  17877. they're ready for action
  17878. @param stopThreadsWhenNotUsedTimeoutMs if this timeout is > 0, then if any threads have been
  17879. inactive for this length of time, they will automatically
  17880. be stopped until more jobs come along and they're needed
  17881. */
  17882. ThreadPool (int numberOfThreads,
  17883. bool startThreadsOnlyWhenNeeded = true,
  17884. int stopThreadsWhenNotUsedTimeoutMs = 5000);
  17885. /** Destructor.
  17886. This will attempt to remove all the jobs before deleting, but if you want to
  17887. specify a timeout, you should call removeAllJobs() explicitly before deleting
  17888. the pool.
  17889. */
  17890. ~ThreadPool();
  17891. /** A callback class used when you need to select which ThreadPoolJob objects are suitable
  17892. for some kind of operation.
  17893. @see ThreadPool::removeAllJobs
  17894. */
  17895. class JUCE_API JobSelector
  17896. {
  17897. public:
  17898. virtual ~JobSelector() {}
  17899. /** Should return true if the specified thread matches your criteria for whatever
  17900. operation that this object is being used for.
  17901. Any implementation of this method must be extremely fast and thread-safe!
  17902. */
  17903. virtual bool isJobSuitable (ThreadPoolJob* job) = 0;
  17904. };
  17905. /** Adds a job to the queue.
  17906. Once a job has been added, then the next time a thread is free, it will run
  17907. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  17908. runJob() method, the pool will either remove the job from the pool or add it to
  17909. the back of the queue to be run again.
  17910. */
  17911. void addJob (ThreadPoolJob* job);
  17912. /** Tries to remove a job from the pool.
  17913. If the job isn't yet running, this will simply remove it. If it is running, it
  17914. will wait for it to finish.
  17915. If the timeout period expires before the job finishes running, then the job will be
  17916. left in the pool and this will return false. It returns true if the job is sucessfully
  17917. stopped and removed.
  17918. @param job the job to remove
  17919. @param interruptIfRunning if true, then if the job is currently busy, its
  17920. ThreadPoolJob::signalJobShouldExit() method will be called to try
  17921. to interrupt it. If false, then if the job will be allowed to run
  17922. until it stops normally (or the timeout expires)
  17923. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  17924. before giving up and returning false
  17925. */
  17926. bool removeJob (ThreadPoolJob* job,
  17927. bool interruptIfRunning,
  17928. int timeOutMilliseconds);
  17929. /** Tries to remove all jobs from the pool.
  17930. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  17931. methods called to try to interrupt them
  17932. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  17933. before giving up and returning false
  17934. @param deleteInactiveJobs if true, any jobs that aren't currently running will be deleted. If false,
  17935. they will simply be removed from the pool. Jobs that are already running when
  17936. this method is called can choose whether they should be deleted by
  17937. returning jobHasFinishedAndShouldBeDeleted from their runJob() method.
  17938. @param selectedJobsToRemove if this is non-zero, the JobSelector object is asked to decide which
  17939. jobs should be removed. If it is zero, all jobs are removed
  17940. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  17941. expires while waiting for one or more jobs to stop
  17942. */
  17943. bool removeAllJobs (bool interruptRunningJobs,
  17944. int timeOutMilliseconds,
  17945. bool deleteInactiveJobs = false,
  17946. JobSelector* selectedJobsToRemove = 0);
  17947. /** Returns the number of jobs currently running or queued.
  17948. */
  17949. int getNumJobs() const;
  17950. /** Returns one of the jobs in the queue.
  17951. Note that this can be a very volatile list as jobs might be continuously getting shifted
  17952. around in the list, and this method may return 0 if the index is currently out-of-range.
  17953. */
  17954. ThreadPoolJob* getJob (int index) const;
  17955. /** Returns true if the given job is currently queued or running.
  17956. @see isJobRunning()
  17957. */
  17958. bool contains (const ThreadPoolJob* job) const;
  17959. /** Returns true if the given job is currently being run by a thread.
  17960. */
  17961. bool isJobRunning (const ThreadPoolJob* job) const;
  17962. /** Waits until a job has finished running and has been removed from the pool.
  17963. This will wait until the job is no longer in the pool - i.e. until its
  17964. runJob() method returns ThreadPoolJob::jobHasFinished.
  17965. If the timeout period expires before the job finishes, this will return false;
  17966. it returns true if the job has finished successfully.
  17967. */
  17968. bool waitForJobToFinish (const ThreadPoolJob* job,
  17969. int timeOutMilliseconds) const;
  17970. /** Returns a list of the names of all the jobs currently running or queued.
  17971. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  17972. */
  17973. StringArray getNamesOfAllJobs (bool onlyReturnActiveJobs) const;
  17974. /** Changes the priority of all the threads.
  17975. This will call Thread::setPriority() for each thread in the pool.
  17976. May return false if for some reason the priority can't be changed.
  17977. */
  17978. bool setThreadPriorities (int newPriority);
  17979. private:
  17980. const int threadStopTimeout;
  17981. int priority;
  17982. class ThreadPoolThread;
  17983. friend class OwnedArray <ThreadPoolThread>;
  17984. OwnedArray <ThreadPoolThread> threads;
  17985. Array <ThreadPoolJob*> jobs;
  17986. CriticalSection lock;
  17987. uint32 lastJobEndTime;
  17988. WaitableEvent jobFinishedSignal;
  17989. friend class ThreadPoolThread;
  17990. bool runNextJob();
  17991. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPool);
  17992. };
  17993. #endif // __JUCE_THREADPOOL_JUCEHEADER__
  17994. /*** End of inlined file: juce_ThreadPool.h ***/
  17995. #endif
  17996. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  17997. /*** Start of inlined file: juce_TimeSliceThread.h ***/
  17998. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  17999. #define __JUCE_TIMESLICETHREAD_JUCEHEADER__
  18000. class TimeSliceThread;
  18001. /**
  18002. Used by the TimeSliceThread class.
  18003. To register your class with a TimeSliceThread, derive from this class and
  18004. use the TimeSliceThread::addTimeSliceClient() method to add it to the list.
  18005. Make sure you always call TimeSliceThread::removeTimeSliceClient() before
  18006. deleting your client!
  18007. @see TimeSliceThread
  18008. */
  18009. class JUCE_API TimeSliceClient
  18010. {
  18011. public:
  18012. /** Destructor. */
  18013. virtual ~TimeSliceClient() {}
  18014. /** Called back by a TimeSliceThread.
  18015. When you register this class with it, a TimeSliceThread will repeatedly call
  18016. this method.
  18017. The implementation of this method should use its time-slice to do something that's
  18018. quick - never block for longer than absolutely necessary.
  18019. @returns Your method should return the number of milliseconds which it would like to wait before being called
  18020. again. Returning 0 will make the thread call again as soon as possible (after possibly servicing
  18021. other busy clients). If you return a value below zero, your client will be removed from the list of clients,
  18022. and won't be called again. The value you specify isn't a guaranteee, and is only used as a hint by the
  18023. thread - the actual time before the next callback may be more or less than specified.
  18024. You can force the TimeSliceThread to wake up and poll again immediately by calling its notify() method.
  18025. */
  18026. virtual int useTimeSlice() = 0;
  18027. private:
  18028. friend class TimeSliceThread;
  18029. Time nextCallTime;
  18030. };
  18031. /**
  18032. A thread that keeps a list of clients, and calls each one in turn, giving them
  18033. all a chance to run some sort of short task.
  18034. @see TimeSliceClient, Thread
  18035. */
  18036. class JUCE_API TimeSliceThread : public Thread
  18037. {
  18038. public:
  18039. /**
  18040. Creates a TimeSliceThread.
  18041. When first created, the thread is not running. Use the startThread()
  18042. method to start it.
  18043. */
  18044. explicit TimeSliceThread (const String& threadName);
  18045. /** Destructor.
  18046. Deleting a Thread object that is running will only give the thread a
  18047. brief opportunity to stop itself cleanly, so it's recommended that you
  18048. should always call stopThread() with a decent timeout before deleting,
  18049. to avoid the thread being forcibly killed (which is a Bad Thing).
  18050. */
  18051. ~TimeSliceThread();
  18052. /** Adds a client to the list.
  18053. The client's callbacks will start after the number of milliseconds specified
  18054. by millisecondsBeforeStarting (and this may happen before this method has returned).
  18055. */
  18056. void addTimeSliceClient (TimeSliceClient* client, int millisecondsBeforeStarting = 0);
  18057. /** Removes a client from the list.
  18058. This method will make sure that all callbacks to the client have completely
  18059. finished before the method returns.
  18060. */
  18061. void removeTimeSliceClient (TimeSliceClient* client);
  18062. /** Returns the number of registered clients. */
  18063. int getNumClients() const;
  18064. /** Returns one of the registered clients. */
  18065. TimeSliceClient* getClient (int index) const;
  18066. #ifndef DOXYGEN
  18067. void run();
  18068. #endif
  18069. private:
  18070. CriticalSection callbackLock, listLock;
  18071. Array <TimeSliceClient*> clients;
  18072. TimeSliceClient* clientBeingCalled;
  18073. TimeSliceClient* getNextClient (int index) const;
  18074. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TimeSliceThread);
  18075. };
  18076. #endif // __JUCE_TIMESLICETHREAD_JUCEHEADER__
  18077. /*** End of inlined file: juce_TimeSliceThread.h ***/
  18078. #endif
  18079. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  18080. #endif
  18081. #endif
  18082. /*** End of inlined file: juce_core_includes.h ***/
  18083. // if you're compiling a command-line app, you might want to just include the core headers,
  18084. // so you can set this macro before including juce.h
  18085. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  18086. /*** Start of inlined file: juce_app_includes.h ***/
  18087. #ifndef __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  18088. #define __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  18089. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  18090. /*** Start of inlined file: juce_Application.h ***/
  18091. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  18092. #define __JUCE_APPLICATION_JUCEHEADER__
  18093. /*** Start of inlined file: juce_ApplicationCommandTarget.h ***/
  18094. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  18095. #define __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  18096. /*** Start of inlined file: juce_Component.h ***/
  18097. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  18098. #define __JUCE_COMPONENT_JUCEHEADER__
  18099. /*** Start of inlined file: juce_MouseCursor.h ***/
  18100. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  18101. #define __JUCE_MOUSECURSOR_JUCEHEADER__
  18102. class Image;
  18103. class ComponentPeer;
  18104. class Component;
  18105. /**
  18106. Represents a mouse cursor image.
  18107. This object can either be used to represent one of the standard mouse
  18108. cursor shapes, or a custom one generated from an image.
  18109. */
  18110. class JUCE_API MouseCursor
  18111. {
  18112. public:
  18113. /** The set of available standard mouse cursors. */
  18114. enum StandardCursorType
  18115. {
  18116. NoCursor = 0, /**< An invisible cursor. */
  18117. NormalCursor, /**< The stardard arrow cursor. */
  18118. WaitCursor, /**< The normal hourglass or spinning-beachball 'busy' cursor. */
  18119. IBeamCursor, /**< A vertical I-beam for positioning within text. */
  18120. CrosshairCursor, /**< A pair of crosshairs. */
  18121. CopyingCursor, /**< The normal arrow cursor, but with a "+" on it to indicate
  18122. that you're dragging a copy of something. */
  18123. PointingHandCursor, /**< A hand with a pointing finger, for clicking on web-links. */
  18124. DraggingHandCursor, /**< An open flat hand for dragging heavy objects around. */
  18125. LeftRightResizeCursor, /**< An arrow pointing left and right. */
  18126. UpDownResizeCursor, /**< an arrow pointing up and down. */
  18127. UpDownLeftRightResizeCursor, /**< An arrow pointing up, down, left and right. */
  18128. TopEdgeResizeCursor, /**< A platform-specific cursor for resizing the top-edge of a window. */
  18129. BottomEdgeResizeCursor, /**< A platform-specific cursor for resizing the bottom-edge of a window. */
  18130. LeftEdgeResizeCursor, /**< A platform-specific cursor for resizing the left-edge of a window. */
  18131. RightEdgeResizeCursor, /**< A platform-specific cursor for resizing the right-edge of a window. */
  18132. TopLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the top-left-corner of a window. */
  18133. TopRightCornerResizeCursor, /**< A platform-specific cursor for resizing the top-right-corner of a window. */
  18134. BottomLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the bottom-left-corner of a window. */
  18135. BottomRightCornerResizeCursor /**< A platform-specific cursor for resizing the bottom-right-corner of a window. */
  18136. };
  18137. /** Creates the standard arrow cursor. */
  18138. MouseCursor();
  18139. /** Creates one of the standard mouse cursor */
  18140. MouseCursor (StandardCursorType type);
  18141. /** Creates a custom cursor from an image.
  18142. @param image the image to use for the cursor - if this is bigger than the
  18143. system can manage, it might get scaled down first, and might
  18144. also have to be turned to black-and-white if it can't do colour
  18145. cursors.
  18146. @param hotSpotX the x position of the cursor's hotspot within the image
  18147. @param hotSpotY the y position of the cursor's hotspot within the image
  18148. */
  18149. MouseCursor (const Image& image, int hotSpotX, int hotSpotY);
  18150. /** Creates a copy of another cursor object. */
  18151. MouseCursor (const MouseCursor& other);
  18152. /** Copies this cursor from another object. */
  18153. MouseCursor& operator= (const MouseCursor& other);
  18154. /** Destructor. */
  18155. ~MouseCursor();
  18156. /** Checks whether two mouse cursors are the same.
  18157. For custom cursors, two cursors created from the same image won't be
  18158. recognised as the same, only MouseCursor objects that have been
  18159. copied from the same object.
  18160. */
  18161. bool operator== (const MouseCursor& other) const noexcept;
  18162. /** Checks whether two mouse cursors are the same.
  18163. For custom cursors, two cursors created from the same image won't be
  18164. recognised as the same, only MouseCursor objects that have been
  18165. copied from the same object.
  18166. */
  18167. bool operator!= (const MouseCursor& other) const noexcept;
  18168. /** Makes the system show its default 'busy' cursor.
  18169. This will turn the system cursor to an hourglass or spinning beachball
  18170. until the next time the mouse is moved, or hideWaitCursor() is called.
  18171. This is handy if the message loop is about to block for a couple of
  18172. seconds while busy and you want to give the user feedback about this.
  18173. @see MessageManager::setTimeBeforeShowingWaitCursor
  18174. */
  18175. static void showWaitCursor();
  18176. /** If showWaitCursor has been called, this will return the mouse to its
  18177. normal state.
  18178. This will look at what component is under the mouse, and update the
  18179. cursor to be the correct one for that component.
  18180. @see showWaitCursor
  18181. */
  18182. static void hideWaitCursor();
  18183. private:
  18184. class SharedCursorHandle;
  18185. friend class SharedCursorHandle;
  18186. SharedCursorHandle* cursorHandle;
  18187. friend class MouseInputSourceInternal;
  18188. void showInWindow (ComponentPeer* window) const;
  18189. void showInAllWindows() const;
  18190. void* getHandle() const noexcept;
  18191. static void* createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY);
  18192. static void* createStandardMouseCursor (MouseCursor::StandardCursorType type);
  18193. static void deleteMouseCursor (void* cursorHandle, bool isStandard);
  18194. JUCE_LEAK_DETECTOR (MouseCursor);
  18195. };
  18196. #endif // __JUCE_MOUSECURSOR_JUCEHEADER__
  18197. /*** End of inlined file: juce_MouseCursor.h ***/
  18198. /*** Start of inlined file: juce_MouseListener.h ***/
  18199. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  18200. #define __JUCE_MOUSELISTENER_JUCEHEADER__
  18201. class MouseEvent;
  18202. /**
  18203. A MouseListener can be registered with a component to receive callbacks
  18204. about mouse events that happen to that component.
  18205. @see Component::addMouseListener, Component::removeMouseListener
  18206. */
  18207. class JUCE_API MouseListener
  18208. {
  18209. public:
  18210. /** Destructor. */
  18211. virtual ~MouseListener() {}
  18212. /** Called when the mouse moves inside a component.
  18213. If the mouse button isn't pressed and the mouse moves over a component,
  18214. this will be called to let the component react to this.
  18215. A component will always get a mouseEnter callback before a mouseMove.
  18216. @param e details about the position and status of the mouse event, including
  18217. the source component in which it occurred
  18218. @see mouseEnter, mouseExit, mouseDrag, contains
  18219. */
  18220. virtual void mouseMove (const MouseEvent& e);
  18221. /** Called when the mouse first enters a component.
  18222. If the mouse button isn't pressed and the mouse moves into a component,
  18223. this will be called to let the component react to this.
  18224. When the mouse button is pressed and held down while being moved in
  18225. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  18226. mouseDrag messages are sent to the component that the mouse was originally
  18227. clicked on, until the button is released.
  18228. @param e details about the position and status of the mouse event, including
  18229. the source component in which it occurred
  18230. @see mouseExit, mouseDrag, mouseMove, contains
  18231. */
  18232. virtual void mouseEnter (const MouseEvent& e);
  18233. /** Called when the mouse moves out of a component.
  18234. This will be called when the mouse moves off the edge of this
  18235. component.
  18236. If the mouse button was pressed, and it was then dragged off the
  18237. edge of the component and released, then this callback will happen
  18238. when the button is released, after the mouseUp callback.
  18239. @param e details about the position and status of the mouse event, including
  18240. the source component in which it occurred
  18241. @see mouseEnter, mouseDrag, mouseMove, contains
  18242. */
  18243. virtual void mouseExit (const MouseEvent& e);
  18244. /** Called when a mouse button is pressed.
  18245. The MouseEvent object passed in contains lots of methods for finding out
  18246. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  18247. were held down at the time.
  18248. Once a button is held down, the mouseDrag method will be called when the
  18249. mouse moves, until the button is released.
  18250. @param e details about the position and status of the mouse event, including
  18251. the source component in which it occurred
  18252. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  18253. */
  18254. virtual void mouseDown (const MouseEvent& e);
  18255. /** Called when the mouse is moved while a button is held down.
  18256. When a mouse button is pressed inside a component, that component
  18257. receives mouseDrag callbacks each time the mouse moves, even if the
  18258. mouse strays outside the component's bounds.
  18259. @param e details about the position and status of the mouse event, including
  18260. the source component in which it occurred
  18261. @see mouseDown, mouseUp, mouseMove, contains, setDragRepeatInterval
  18262. */
  18263. virtual void mouseDrag (const MouseEvent& e);
  18264. /** Called when a mouse button is released.
  18265. A mouseUp callback is sent to the component in which a button was pressed
  18266. even if the mouse is actually over a different component when the
  18267. button is released.
  18268. The MouseEvent object passed in contains lots of methods for finding out
  18269. which buttons were down just before they were released.
  18270. @param e details about the position and status of the mouse event, including
  18271. the source component in which it occurred
  18272. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  18273. */
  18274. virtual void mouseUp (const MouseEvent& e);
  18275. /** Called when a mouse button has been double-clicked on a component.
  18276. The MouseEvent object passed in contains lots of methods for finding out
  18277. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  18278. were held down at the time.
  18279. @param e details about the position and status of the mouse event, including
  18280. the source component in which it occurred
  18281. @see mouseDown, mouseUp
  18282. */
  18283. virtual void mouseDoubleClick (const MouseEvent& e);
  18284. /** Called when the mouse-wheel is moved.
  18285. This callback is sent to the component that the mouse is over when the
  18286. wheel is moved.
  18287. If not overridden, the component will forward this message to its parent, so
  18288. that parent components can collect mouse-wheel messages that happen to
  18289. child components which aren't interested in them.
  18290. @param e details about the position and status of the mouse event, including
  18291. the source component in which it occurred
  18292. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  18293. value means the wheel has been pushed to the right, negative means it
  18294. was pushed to the left
  18295. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  18296. value means the wheel has been pushed upwards, negative means it
  18297. was pushed downwards
  18298. */
  18299. virtual void mouseWheelMove (const MouseEvent& e,
  18300. float wheelIncrementX,
  18301. float wheelIncrementY);
  18302. };
  18303. #endif // __JUCE_MOUSELISTENER_JUCEHEADER__
  18304. /*** End of inlined file: juce_MouseListener.h ***/
  18305. /*** Start of inlined file: juce_MouseEvent.h ***/
  18306. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  18307. #define __JUCE_MOUSEEVENT_JUCEHEADER__
  18308. class Component;
  18309. class MouseInputSource;
  18310. /*** Start of inlined file: juce_ModifierKeys.h ***/
  18311. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  18312. #define __JUCE_MODIFIERKEYS_JUCEHEADER__
  18313. /**
  18314. Represents the state of the mouse buttons and modifier keys.
  18315. This is used both by mouse events and by KeyPress objects to describe
  18316. the state of keys such as shift, control, alt, etc.
  18317. @see KeyPress, MouseEvent::mods
  18318. */
  18319. class JUCE_API ModifierKeys
  18320. {
  18321. public:
  18322. /** Creates a ModifierKeys object from a raw set of flags.
  18323. @param flags to represent the keys that are down
  18324. @see shiftModifier, ctrlModifier, altModifier, leftButtonModifier,
  18325. rightButtonModifier, commandModifier, popupMenuClickModifier
  18326. */
  18327. ModifierKeys (int flags = 0) noexcept;
  18328. /** Creates a copy of another object. */
  18329. ModifierKeys (const ModifierKeys& other) noexcept;
  18330. /** Copies this object from another one. */
  18331. ModifierKeys& operator= (const ModifierKeys& other) noexcept;
  18332. /** Checks whether the 'command' key flag is set (or 'ctrl' on Windows/Linux).
  18333. This is a platform-agnostic way of checking for the operating system's
  18334. preferred command-key modifier - so on the Mac it tests for the Apple key, on
  18335. Windows/Linux, it's actually checking for the CTRL key.
  18336. */
  18337. inline bool isCommandDown() const noexcept { return (flags & commandModifier) != 0; }
  18338. /** Checks whether the user is trying to launch a pop-up menu.
  18339. This checks for platform-specific modifiers that might indicate that the user
  18340. is following the operating system's normal method of showing a pop-up menu.
  18341. So on Windows/Linux, this method is really testing for a right-click.
  18342. On the Mac, it tests for either the CTRL key being down, or a right-click.
  18343. */
  18344. inline bool isPopupMenu() const noexcept { return (flags & popupMenuClickModifier) != 0; }
  18345. /** Checks whether the flag is set for the left mouse-button. */
  18346. inline bool isLeftButtonDown() const noexcept { return (flags & leftButtonModifier) != 0; }
  18347. /** Checks whether the flag is set for the right mouse-button.
  18348. Note that for detecting popup-menu clicks, you should be using isPopupMenu() instead, as
  18349. this is platform-independent (and makes your code more explanatory too).
  18350. */
  18351. inline bool isRightButtonDown() const noexcept { return (flags & rightButtonModifier) != 0; }
  18352. inline bool isMiddleButtonDown() const noexcept { return (flags & middleButtonModifier) != 0; }
  18353. /** Tests for any of the mouse-button flags. */
  18354. inline bool isAnyMouseButtonDown() const noexcept { return (flags & allMouseButtonModifiers) != 0; }
  18355. /** Tests for any of the modifier key flags. */
  18356. inline bool isAnyModifierKeyDown() const noexcept { return (flags & (shiftModifier | ctrlModifier | altModifier | commandModifier)) != 0; }
  18357. /** Checks whether the shift key's flag is set. */
  18358. inline bool isShiftDown() const noexcept { return (flags & shiftModifier) != 0; }
  18359. /** Checks whether the CTRL key's flag is set.
  18360. Remember that it's better to use the platform-agnostic routines to test for command-key and
  18361. popup-menu modifiers.
  18362. @see isCommandDown, isPopupMenu
  18363. */
  18364. inline bool isCtrlDown() const noexcept { return (flags & ctrlModifier) != 0; }
  18365. /** Checks whether the shift key's flag is set. */
  18366. inline bool isAltDown() const noexcept { return (flags & altModifier) != 0; }
  18367. /** Flags that represent the different keys. */
  18368. enum Flags
  18369. {
  18370. /** Shift key flag. */
  18371. shiftModifier = 1,
  18372. /** CTRL key flag. */
  18373. ctrlModifier = 2,
  18374. /** ALT key flag. */
  18375. altModifier = 4,
  18376. /** Left mouse button flag. */
  18377. leftButtonModifier = 16,
  18378. /** Right mouse button flag. */
  18379. rightButtonModifier = 32,
  18380. /** Middle mouse button flag. */
  18381. middleButtonModifier = 64,
  18382. #if JUCE_MAC
  18383. /** Command key flag - on windows this is the same as the CTRL key flag. */
  18384. commandModifier = 8,
  18385. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  18386. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  18387. popupMenuClickModifier = rightButtonModifier | ctrlModifier,
  18388. #else
  18389. /** Command key flag - on windows this is the same as the CTRL key flag. */
  18390. commandModifier = ctrlModifier,
  18391. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  18392. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  18393. popupMenuClickModifier = rightButtonModifier,
  18394. #endif
  18395. /** Represents a combination of all the shift, alt, ctrl and command key modifiers. */
  18396. allKeyboardModifiers = shiftModifier | ctrlModifier | altModifier | commandModifier,
  18397. /** Represents a combination of all the mouse buttons at once. */
  18398. allMouseButtonModifiers = leftButtonModifier | rightButtonModifier | middleButtonModifier,
  18399. };
  18400. /** Returns a copy of only the mouse-button flags */
  18401. const ModifierKeys withOnlyMouseButtons() const noexcept { return ModifierKeys (flags & allMouseButtonModifiers); }
  18402. /** Returns a copy of only the non-mouse flags */
  18403. const ModifierKeys withoutMouseButtons() const noexcept { return ModifierKeys (flags & ~allMouseButtonModifiers); }
  18404. bool operator== (const ModifierKeys& other) const noexcept { return flags == other.flags; }
  18405. bool operator!= (const ModifierKeys& other) const noexcept { return flags != other.flags; }
  18406. /** Returns the raw flags for direct testing. */
  18407. inline int getRawFlags() const noexcept { return flags; }
  18408. inline const ModifierKeys withoutFlags (int rawFlagsToClear) const noexcept { return ModifierKeys (flags & ~rawFlagsToClear); }
  18409. inline const ModifierKeys withFlags (int rawFlagsToSet) const noexcept { return ModifierKeys (flags | rawFlagsToSet); }
  18410. /** Tests a combination of flags and returns true if any of them are set. */
  18411. inline bool testFlags (const int flagsToTest) const noexcept { return (flags & flagsToTest) != 0; }
  18412. /** Returns the total number of mouse buttons that are down. */
  18413. int getNumMouseButtonsDown() const noexcept;
  18414. /** Creates a ModifierKeys object to represent the last-known state of the
  18415. keyboard and mouse buttons.
  18416. @see getCurrentModifiersRealtime
  18417. */
  18418. static const ModifierKeys getCurrentModifiers() noexcept;
  18419. /** Creates a ModifierKeys object to represent the current state of the
  18420. keyboard and mouse buttons.
  18421. This isn't often needed and isn't recommended, but will actively check all the
  18422. mouse and key states rather than just returning their last-known state like
  18423. getCurrentModifiers() does.
  18424. This is only needed in special circumstances for up-to-date modifier information
  18425. at times when the app's event loop isn't running normally.
  18426. Another reason to avoid this method is that it's not stateless, and calling it may
  18427. update the value returned by getCurrentModifiers(), which could cause subtle changes
  18428. in the behaviour of some components.
  18429. */
  18430. static const ModifierKeys getCurrentModifiersRealtime() noexcept;
  18431. private:
  18432. int flags;
  18433. static ModifierKeys currentModifiers;
  18434. friend class ComponentPeer;
  18435. friend class MouseInputSource;
  18436. friend class MouseInputSourceInternal;
  18437. static void updateCurrentModifiers() noexcept;
  18438. };
  18439. #endif // __JUCE_MODIFIERKEYS_JUCEHEADER__
  18440. /*** End of inlined file: juce_ModifierKeys.h ***/
  18441. /*** Start of inlined file: juce_Point.h ***/
  18442. #ifndef __JUCE_POINT_JUCEHEADER__
  18443. #define __JUCE_POINT_JUCEHEADER__
  18444. /*** Start of inlined file: juce_AffineTransform.h ***/
  18445. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  18446. #define __JUCE_AFFINETRANSFORM_JUCEHEADER__
  18447. /**
  18448. Represents a 2D affine-transformation matrix.
  18449. An affine transformation is a transformation such as a rotation, scale, shear,
  18450. resize or translation.
  18451. These are used for various 2D transformation tasks, e.g. with Path objects.
  18452. @see Path, Point, Line
  18453. */
  18454. class JUCE_API AffineTransform
  18455. {
  18456. public:
  18457. /** Creates an identity transform. */
  18458. AffineTransform() noexcept;
  18459. /** Creates a copy of another transform. */
  18460. AffineTransform (const AffineTransform& other) noexcept;
  18461. /** Creates a transform from a set of raw matrix values.
  18462. The resulting matrix is:
  18463. (mat00 mat01 mat02)
  18464. (mat10 mat11 mat12)
  18465. ( 0 0 1 )
  18466. */
  18467. AffineTransform (float mat00, float mat01, float mat02,
  18468. float mat10, float mat11, float mat12) noexcept;
  18469. /** Copies from another AffineTransform object */
  18470. AffineTransform& operator= (const AffineTransform& other) noexcept;
  18471. /** Compares two transforms. */
  18472. bool operator== (const AffineTransform& other) const noexcept;
  18473. /** Compares two transforms. */
  18474. bool operator!= (const AffineTransform& other) const noexcept;
  18475. /** A ready-to-use identity transform, which you can use to append other
  18476. transformations to.
  18477. e.g. @code
  18478. AffineTransform myTransform = AffineTransform::identity.rotated (.5f)
  18479. .scaled (2.0f);
  18480. @endcode
  18481. */
  18482. static const AffineTransform identity;
  18483. /** Transforms a 2D co-ordinate using this matrix. */
  18484. template <typename ValueType>
  18485. void transformPoint (ValueType& x, ValueType& y) const noexcept
  18486. {
  18487. const ValueType oldX = x;
  18488. x = static_cast <ValueType> (mat00 * oldX + mat01 * y + mat02);
  18489. y = static_cast <ValueType> (mat10 * oldX + mat11 * y + mat12);
  18490. }
  18491. /** Transforms two 2D co-ordinates using this matrix.
  18492. This is just a shortcut for calling transformPoint() on each of these pairs of
  18493. coordinates in turn. (And putting all the calculations into one function hopefully
  18494. also gives the compiler a bit more scope for pipelining it).
  18495. */
  18496. template <typename ValueType>
  18497. void transformPoints (ValueType& x1, ValueType& y1,
  18498. ValueType& x2, ValueType& y2) const noexcept
  18499. {
  18500. const ValueType oldX1 = x1, oldX2 = x2;
  18501. x1 = static_cast <ValueType> (mat00 * oldX1 + mat01 * y1 + mat02);
  18502. y1 = static_cast <ValueType> (mat10 * oldX1 + mat11 * y1 + mat12);
  18503. x2 = static_cast <ValueType> (mat00 * oldX2 + mat01 * y2 + mat02);
  18504. y2 = static_cast <ValueType> (mat10 * oldX2 + mat11 * y2 + mat12);
  18505. }
  18506. /** Transforms three 2D co-ordinates using this matrix.
  18507. This is just a shortcut for calling transformPoint() on each of these pairs of
  18508. coordinates in turn. (And putting all the calculations into one function hopefully
  18509. also gives the compiler a bit more scope for pipelining it).
  18510. */
  18511. template <typename ValueType>
  18512. void transformPoints (ValueType& x1, ValueType& y1,
  18513. ValueType& x2, ValueType& y2,
  18514. ValueType& x3, ValueType& y3) const noexcept
  18515. {
  18516. const ValueType oldX1 = x1, oldX2 = x2, oldX3 = x3;
  18517. x1 = static_cast <ValueType> (mat00 * oldX1 + mat01 * y1 + mat02);
  18518. y1 = static_cast <ValueType> (mat10 * oldX1 + mat11 * y1 + mat12);
  18519. x2 = static_cast <ValueType> (mat00 * oldX2 + mat01 * y2 + mat02);
  18520. y2 = static_cast <ValueType> (mat10 * oldX2 + mat11 * y2 + mat12);
  18521. x3 = static_cast <ValueType> (mat00 * oldX3 + mat01 * y3 + mat02);
  18522. y3 = static_cast <ValueType> (mat10 * oldX3 + mat11 * y3 + mat12);
  18523. }
  18524. /** Returns a new transform which is the same as this one followed by a translation. */
  18525. AffineTransform translated (float deltaX,
  18526. float deltaY) const noexcept;
  18527. /** Returns a new transform which is a translation. */
  18528. static AffineTransform translation (float deltaX,
  18529. float deltaY) noexcept;
  18530. /** Returns a transform which is the same as this one followed by a rotation.
  18531. The rotation is specified by a number of radians to rotate clockwise, centred around
  18532. the origin (0, 0).
  18533. */
  18534. AffineTransform rotated (float angleInRadians) const noexcept;
  18535. /** Returns a transform which is the same as this one followed by a rotation about a given point.
  18536. The rotation is specified by a number of radians to rotate clockwise, centred around
  18537. the co-ordinates passed in.
  18538. */
  18539. AffineTransform rotated (float angleInRadians,
  18540. float pivotX,
  18541. float pivotY) const noexcept;
  18542. /** Returns a new transform which is a rotation about (0, 0). */
  18543. static AffineTransform rotation (float angleInRadians) noexcept;
  18544. /** Returns a new transform which is a rotation about a given point. */
  18545. static AffineTransform rotation (float angleInRadians,
  18546. float pivotX,
  18547. float pivotY) noexcept;
  18548. /** Returns a transform which is the same as this one followed by a re-scaling.
  18549. The scaling is centred around the origin (0, 0).
  18550. */
  18551. AffineTransform scaled (float factorX,
  18552. float factorY) const noexcept;
  18553. /** Returns a transform which is the same as this one followed by a re-scaling.
  18554. The scaling is centred around the origin provided.
  18555. */
  18556. AffineTransform scaled (float factorX, float factorY,
  18557. float pivotX, float pivotY) const noexcept;
  18558. /** Returns a new transform which is a re-scale about the origin. */
  18559. static AffineTransform scale (float factorX,
  18560. float factorY) noexcept;
  18561. /** Returns a new transform which is a re-scale centred around the point provided. */
  18562. static AffineTransform scale (float factorX, float factorY,
  18563. float pivotX, float pivotY) noexcept;
  18564. /** Returns a transform which is the same as this one followed by a shear.
  18565. The shear is centred around the origin (0, 0).
  18566. */
  18567. AffineTransform sheared (float shearX, float shearY) const noexcept;
  18568. /** Returns a shear transform, centred around the origin (0, 0). */
  18569. static AffineTransform shear (float shearX, float shearY) noexcept;
  18570. /** Returns a matrix which is the inverse operation of this one.
  18571. Some matrices don't have an inverse - in this case, the method will just return
  18572. an identity transform.
  18573. */
  18574. AffineTransform inverted() const noexcept;
  18575. /** Returns the transform that will map three known points onto three coordinates
  18576. that are supplied.
  18577. This returns the transform that will transform (0, 0) into (x00, y00),
  18578. (1, 0) to (x10, y10), and (0, 1) to (x01, y01).
  18579. */
  18580. static AffineTransform fromTargetPoints (float x00, float y00,
  18581. float x10, float y10,
  18582. float x01, float y01) noexcept;
  18583. /** Returns the transform that will map three specified points onto three target points.
  18584. */
  18585. static AffineTransform fromTargetPoints (float sourceX1, float sourceY1, float targetX1, float targetY1,
  18586. float sourceX2, float sourceY2, float targetX2, float targetY2,
  18587. float sourceX3, float sourceY3, float targetX3, float targetY3) noexcept;
  18588. /** Returns the result of concatenating another transformation after this one. */
  18589. AffineTransform followedBy (const AffineTransform& other) const noexcept;
  18590. /** Returns true if this transform has no effect on points. */
  18591. bool isIdentity() const noexcept;
  18592. /** Returns true if this transform maps to a singularity - i.e. if it has no inverse. */
  18593. bool isSingularity() const noexcept;
  18594. /** Returns true if the transform only translates, and doesn't scale or rotate the
  18595. points. */
  18596. bool isOnlyTranslation() const noexcept;
  18597. /** If this transform is only a translation, this returns the X offset.
  18598. @see isOnlyTranslation
  18599. */
  18600. float getTranslationX() const noexcept { return mat02; }
  18601. /** If this transform is only a translation, this returns the X offset.
  18602. @see isOnlyTranslation
  18603. */
  18604. float getTranslationY() const noexcept { return mat12; }
  18605. /** Returns the approximate scale factor by which lengths will be transformed.
  18606. Obviously a length may be scaled by entirely different amounts depending on its
  18607. direction, so this is only appropriate as a rough guide.
  18608. */
  18609. float getScaleFactor() const noexcept;
  18610. /* The transform matrix is:
  18611. (mat00 mat01 mat02)
  18612. (mat10 mat11 mat12)
  18613. ( 0 0 1 )
  18614. */
  18615. float mat00, mat01, mat02;
  18616. float mat10, mat11, mat12;
  18617. private:
  18618. JUCE_LEAK_DETECTOR (AffineTransform);
  18619. };
  18620. #endif // __JUCE_AFFINETRANSFORM_JUCEHEADER__
  18621. /*** End of inlined file: juce_AffineTransform.h ***/
  18622. /**
  18623. A pair of (x, y) co-ordinates.
  18624. The ValueType template should be a primitive type such as int, float, double,
  18625. rather than a class.
  18626. @see Line, Path, AffineTransform
  18627. */
  18628. template <typename ValueType>
  18629. class Point
  18630. {
  18631. public:
  18632. /** Creates a point with co-ordinates (0, 0). */
  18633. Point() noexcept : x(), y() {}
  18634. /** Creates a copy of another point. */
  18635. Point (const Point& other) noexcept : x (other.x), y (other.y) {}
  18636. /** Creates a point from an (x, y) position. */
  18637. Point (const ValueType initialX, const ValueType initialY) noexcept : x (initialX), y (initialY) {}
  18638. /** Destructor. */
  18639. ~Point() noexcept {}
  18640. /** Copies this point from another one. */
  18641. Point& operator= (const Point& other) noexcept { x = other.x; y = other.y; return *this; }
  18642. inline bool operator== (const Point& other) const noexcept { return x == other.x && y == other.y; }
  18643. inline bool operator!= (const Point& other) const noexcept { return x != other.x || y != other.y; }
  18644. /** Returns true if the point is (0, 0). */
  18645. bool isOrigin() const noexcept { return x == ValueType() && y == ValueType(); }
  18646. /** Returns the point's x co-ordinate. */
  18647. inline ValueType getX() const noexcept { return x; }
  18648. /** Returns the point's y co-ordinate. */
  18649. inline ValueType getY() const noexcept { return y; }
  18650. /** Sets the point's x co-ordinate. */
  18651. inline void setX (const ValueType newX) noexcept { x = newX; }
  18652. /** Sets the point's y co-ordinate. */
  18653. inline void setY (const ValueType newY) noexcept { y = newY; }
  18654. /** Returns a point which has the same Y position as this one, but a new X. */
  18655. Point withX (const ValueType newX) const noexcept { return Point (newX, y); }
  18656. /** Returns a point which has the same X position as this one, but a new Y. */
  18657. Point withY (const ValueType newY) const noexcept { return Point (x, newY); }
  18658. /** Changes the point's x and y co-ordinates. */
  18659. void setXY (const ValueType newX, const ValueType newY) noexcept { x = newX; y = newY; }
  18660. /** Adds a pair of co-ordinates to this value. */
  18661. void addXY (const ValueType xToAdd, const ValueType yToAdd) noexcept { x += xToAdd; y += yToAdd; }
  18662. /** Returns a point with a given offset from this one. */
  18663. Point translated (const ValueType xDelta, const ValueType yDelta) const noexcept { return Point (x + xDelta, y + yDelta); }
  18664. /** Adds two points together. */
  18665. Point operator+ (const Point& other) const noexcept { return Point (x + other.x, y + other.y); }
  18666. /** Adds another point's co-ordinates to this one. */
  18667. Point& operator+= (const Point& other) noexcept { x += other.x; y += other.y; return *this; }
  18668. /** Subtracts one points from another. */
  18669. Point operator- (const Point& other) const noexcept { return Point (x - other.x, y - other.y); }
  18670. /** Subtracts another point's co-ordinates to this one. */
  18671. Point& operator-= (const Point& other) noexcept { x -= other.x; y -= other.y; return *this; }
  18672. /** Returns a point whose coordinates are multiplied by a given value. */
  18673. Point operator* (const ValueType multiplier) const noexcept { return Point (x * multiplier, y * multiplier); }
  18674. /** Multiplies the point's co-ordinates by a value. */
  18675. Point& operator*= (const ValueType multiplier) noexcept { x *= multiplier; y *= multiplier; return *this; }
  18676. /** Returns a point whose coordinates are divided by a given value. */
  18677. Point operator/ (const ValueType divisor) const noexcept { return Point (x / divisor, y / divisor); }
  18678. /** Divides the point's co-ordinates by a value. */
  18679. Point& operator/= (const ValueType divisor) noexcept { x /= divisor; y /= divisor; return *this; }
  18680. /** Returns the inverse of this point. */
  18681. Point operator-() const noexcept { return Point (-x, -y); }
  18682. /** Returns the straight-line distance between this point and another one. */
  18683. ValueType getDistanceFromOrigin() const noexcept { return juce_hypot (x, y); }
  18684. /** Returns the straight-line distance between this point and another one. */
  18685. ValueType getDistanceFrom (const Point& other) const noexcept { return juce_hypot (x - other.x, y - other.y); }
  18686. /** Returns the angle from this point to another one.
  18687. The return value is the number of radians clockwise from the 3 o'clock direction,
  18688. where this point is the centre and the other point is on the circumference.
  18689. */
  18690. ValueType getAngleToPoint (const Point& other) const noexcept { return (ValueType) std::atan2 (other.x - x, other.y - y); }
  18691. /** Taking this point to be the centre of a circle, this returns a point on its circumference.
  18692. @param radius the radius of the circle.
  18693. @param angle the angle of the point, in radians clockwise from the 12 o'clock position.
  18694. */
  18695. Point getPointOnCircumference (const float radius, const float angle) const noexcept { return Point<float> (x + radius * std::sin (angle),
  18696. y - radius * std::cos (angle)); }
  18697. /** Taking this point to be the centre of an ellipse, this returns a point on its circumference.
  18698. @param radiusX the horizontal radius of the circle.
  18699. @param radiusY the vertical radius of the circle.
  18700. @param angle the angle of the point, in radians clockwise from the 12 o'clock position.
  18701. */
  18702. Point getPointOnCircumference (const float radiusX, const float radiusY, const float angle) const noexcept { return Point<float> (x + radiusX * std::sin (angle),
  18703. y - radiusY * std::cos (angle)); }
  18704. /** Uses a transform to change the point's co-ordinates.
  18705. This will only compile if ValueType = float!
  18706. @see AffineTransform::transformPoint
  18707. */
  18708. void applyTransform (const AffineTransform& transform) noexcept { transform.transformPoint (x, y); }
  18709. /** Returns the position of this point, if it is transformed by a given AffineTransform. */
  18710. Point transformedBy (const AffineTransform& transform) const noexcept { return Point (transform.mat00 * x + transform.mat01 * y + transform.mat02,
  18711. transform.mat10 * x + transform.mat11 * y + transform.mat12); }
  18712. /** Casts this point to a Point<int> object. */
  18713. Point<int> toInt() const noexcept { return Point<int> (static_cast <int> (x), static_cast<int> (y)); }
  18714. /** Casts this point to a Point<float> object. */
  18715. Point<float> toFloat() const noexcept { return Point<float> (static_cast <float> (x), static_cast<float> (y)); }
  18716. /** Casts this point to a Point<double> object. */
  18717. Point<double> toDouble() const noexcept { return Point<double> (static_cast <double> (x), static_cast<double> (y)); }
  18718. /** Returns the point as a string in the form "x, y". */
  18719. String toString() const { return String (x) + ", " + String (y); }
  18720. private:
  18721. ValueType x, y;
  18722. };
  18723. #endif // __JUCE_POINT_JUCEHEADER__
  18724. /*** End of inlined file: juce_Point.h ***/
  18725. /**
  18726. Contains position and status information about a mouse event.
  18727. @see MouseListener, Component::mouseMove, Component::mouseEnter, Component::mouseExit,
  18728. Component::mouseDown, Component::mouseUp, Component::mouseDrag
  18729. */
  18730. class JUCE_API MouseEvent
  18731. {
  18732. public:
  18733. /** Creates a MouseEvent.
  18734. Normally an application will never need to use this.
  18735. @param source the source that's invoking the event
  18736. @param position the position of the mouse, relative to the component that is passed-in
  18737. @param modifiers the key modifiers at the time of the event
  18738. @param eventComponent the component that the mouse event applies to
  18739. @param originator the component that originally received the event
  18740. @param eventTime the time the event happened
  18741. @param mouseDownPos the position of the corresponding mouse-down event (relative to the component that is passed-in).
  18742. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  18743. the same as the current mouse-x position.
  18744. @param mouseDownTime the time at which the corresponding mouse-down event happened
  18745. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  18746. the same as the current mouse-event time.
  18747. @param numberOfClicks how many clicks, e.g. a double-click event will be 2, a triple-click will be 3, etc
  18748. @param mouseWasDragged whether the mouse has been dragged significantly since the previous mouse-down
  18749. */
  18750. MouseEvent (MouseInputSource& source,
  18751. const Point<int>& position,
  18752. const ModifierKeys& modifiers,
  18753. Component* eventComponent,
  18754. Component* originator,
  18755. const Time& eventTime,
  18756. const Point<int> mouseDownPos,
  18757. const Time& mouseDownTime,
  18758. int numberOfClicks,
  18759. bool mouseWasDragged) noexcept;
  18760. /** Destructor. */
  18761. ~MouseEvent() noexcept;
  18762. /** The x-position of the mouse when the event occurred.
  18763. This value is relative to the top-left of the component to which the
  18764. event applies (as indicated by the MouseEvent::eventComponent field).
  18765. */
  18766. const int x;
  18767. /** The y-position of the mouse when the event occurred.
  18768. This value is relative to the top-left of the component to which the
  18769. event applies (as indicated by the MouseEvent::eventComponent field).
  18770. */
  18771. const int y;
  18772. /** The key modifiers associated with the event.
  18773. This will let you find out which mouse buttons were down, as well as which
  18774. modifier keys were held down.
  18775. When used for mouse-up events, this will indicate the state of the mouse buttons
  18776. just before they were released, so that you can tell which button they let go of.
  18777. */
  18778. const ModifierKeys mods;
  18779. /** The component that this event applies to.
  18780. This is usually the component that the mouse was over at the time, but for mouse-drag
  18781. events the mouse could actually be over a different component and the events are
  18782. still sent to the component that the button was originally pressed on.
  18783. The x and y member variables are relative to this component's position.
  18784. If you use getEventRelativeTo() to retarget this object to be relative to a different
  18785. component, this pointer will be updated, but originalComponent remains unchanged.
  18786. @see originalComponent
  18787. */
  18788. Component* const eventComponent;
  18789. /** The component that the event first occurred on.
  18790. If you use getEventRelativeTo() to retarget this object to be relative to a different
  18791. component, this value remains unchanged to indicate the first component that received it.
  18792. @see eventComponent
  18793. */
  18794. Component* const originalComponent;
  18795. /** The time that this mouse-event occurred.
  18796. */
  18797. const Time eventTime;
  18798. /** The source device that generated this event.
  18799. */
  18800. MouseInputSource& source;
  18801. /** Returns the x co-ordinate of the last place that a mouse was pressed.
  18802. The co-ordinate is relative to the component specified in MouseEvent::component.
  18803. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  18804. */
  18805. int getMouseDownX() const noexcept;
  18806. /** Returns the y co-ordinate of the last place that a mouse was pressed.
  18807. The co-ordinate is relative to the component specified in MouseEvent::component.
  18808. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  18809. */
  18810. int getMouseDownY() const noexcept;
  18811. /** Returns the co-ordinates of the last place that a mouse was pressed.
  18812. The co-ordinates are relative to the component specified in MouseEvent::component.
  18813. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  18814. */
  18815. const Point<int> getMouseDownPosition() const noexcept;
  18816. /** Returns the straight-line distance between where the mouse is now and where it
  18817. was the last time the button was pressed.
  18818. This is quite handy for things like deciding whether the user has moved far enough
  18819. for it to be considered a drag operation.
  18820. @see getDistanceFromDragStartX
  18821. */
  18822. int getDistanceFromDragStart() const noexcept;
  18823. /** Returns the difference between the mouse's current x postion and where it was
  18824. when the button was last pressed.
  18825. @see getDistanceFromDragStart
  18826. */
  18827. int getDistanceFromDragStartX() const noexcept;
  18828. /** Returns the difference between the mouse's current y postion and where it was
  18829. when the button was last pressed.
  18830. @see getDistanceFromDragStart
  18831. */
  18832. int getDistanceFromDragStartY() const noexcept;
  18833. /** Returns the difference between the mouse's current postion and where it was
  18834. when the button was last pressed.
  18835. @see getDistanceFromDragStart
  18836. */
  18837. const Point<int> getOffsetFromDragStart() const noexcept;
  18838. /** Returns true if the mouse has just been clicked.
  18839. Used in either your mouseUp() or mouseDrag() methods, this will tell you whether
  18840. the user has dragged the mouse more than a few pixels from the place where the
  18841. mouse-down occurred.
  18842. Once they have dragged it far enough for this method to return false, it will continue
  18843. to return false until the mouse-up, even if they move the mouse back to the same
  18844. position where they originally pressed it. This means that it's very handy for
  18845. objects that can either be clicked on or dragged, as you can use it in the mouseDrag()
  18846. callback to ignore any small movements they might make while clicking.
  18847. @returns true if the mouse wasn't dragged by more than a few pixels between
  18848. the last time the button was pressed and released.
  18849. */
  18850. bool mouseWasClicked() const noexcept;
  18851. /** For a click event, the number of times the mouse was clicked in succession.
  18852. So for example a double-click event will return 2, a triple-click 3, etc.
  18853. */
  18854. int getNumberOfClicks() const noexcept { return numberOfClicks; }
  18855. /** Returns the time that the mouse button has been held down for.
  18856. If called from a mouseDrag or mouseUp callback, this will return the
  18857. number of milliseconds since the corresponding mouseDown event occurred.
  18858. If called in other contexts, e.g. a mouseMove, then the returned value
  18859. may be 0 or an undefined value.
  18860. */
  18861. int getLengthOfMousePress() const noexcept;
  18862. /** The position of the mouse when the event occurred.
  18863. This position is relative to the top-left of the component to which the
  18864. event applies (as indicated by the MouseEvent::eventComponent field).
  18865. */
  18866. const Point<int> getPosition() const noexcept;
  18867. /** Returns the mouse x position of this event, in global screen co-ordinates.
  18868. The co-ordinates are relative to the top-left of the main monitor.
  18869. @see getScreenPosition
  18870. */
  18871. int getScreenX() const;
  18872. /** Returns the mouse y position of this event, in global screen co-ordinates.
  18873. The co-ordinates are relative to the top-left of the main monitor.
  18874. @see getScreenPosition
  18875. */
  18876. int getScreenY() const;
  18877. /** Returns the mouse position of this event, in global screen co-ordinates.
  18878. The co-ordinates are relative to the top-left of the main monitor.
  18879. @see getMouseDownScreenPosition
  18880. */
  18881. const Point<int> getScreenPosition() const;
  18882. /** Returns the x co-ordinate at which the mouse button was last pressed.
  18883. The co-ordinates are relative to the top-left of the main monitor.
  18884. @see getMouseDownScreenPosition
  18885. */
  18886. int getMouseDownScreenX() const;
  18887. /** Returns the y co-ordinate at which the mouse button was last pressed.
  18888. The co-ordinates are relative to the top-left of the main monitor.
  18889. @see getMouseDownScreenPosition
  18890. */
  18891. int getMouseDownScreenY() const;
  18892. /** Returns the co-ordinates at which the mouse button was last pressed.
  18893. The co-ordinates are relative to the top-left of the main monitor.
  18894. @see getScreenPosition
  18895. */
  18896. const Point<int> getMouseDownScreenPosition() const;
  18897. /** Creates a version of this event that is relative to a different component.
  18898. The x and y positions of the event that is returned will have been
  18899. adjusted to be relative to the new component.
  18900. */
  18901. MouseEvent getEventRelativeTo (Component* otherComponent) const noexcept;
  18902. /** Creates a copy of this event with a different position.
  18903. All other members of the event object are the same, but the x and y are
  18904. replaced with these new values.
  18905. */
  18906. MouseEvent withNewPosition (const Point<int>& newPosition) const noexcept;
  18907. /** Changes the application-wide setting for the double-click time limit.
  18908. This is the maximum length of time between mouse-clicks for it to be
  18909. considered a double-click. It's used by the Component class.
  18910. @see getDoubleClickTimeout, MouseListener::mouseDoubleClick
  18911. */
  18912. static void setDoubleClickTimeout (int timeOutMilliseconds) noexcept;
  18913. /** Returns the application-wide setting for the double-click time limit.
  18914. This is the maximum length of time between mouse-clicks for it to be
  18915. considered a double-click. It's used by the Component class.
  18916. @see setDoubleClickTimeout, MouseListener::mouseDoubleClick
  18917. */
  18918. static int getDoubleClickTimeout() noexcept;
  18919. private:
  18920. const Point<int> mouseDownPos;
  18921. const Time mouseDownTime;
  18922. const int numberOfClicks;
  18923. const bool wasMovedSinceMouseDown;
  18924. static int doubleClickTimeOutMs;
  18925. MouseEvent& operator= (const MouseEvent&);
  18926. };
  18927. #endif // __JUCE_MOUSEEVENT_JUCEHEADER__
  18928. /*** End of inlined file: juce_MouseEvent.h ***/
  18929. /*** Start of inlined file: juce_ComponentListener.h ***/
  18930. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  18931. #define __JUCE_COMPONENTLISTENER_JUCEHEADER__
  18932. class Component;
  18933. /**
  18934. Gets informed about changes to a component's hierarchy or position.
  18935. To monitor a component for changes, register a subclass of ComponentListener
  18936. with the component using Component::addComponentListener().
  18937. Be sure to deregister listeners before you delete them!
  18938. @see Component::addComponentListener, Component::removeComponentListener
  18939. */
  18940. class JUCE_API ComponentListener
  18941. {
  18942. public:
  18943. /** Destructor. */
  18944. virtual ~ComponentListener() {}
  18945. /** Called when the component's position or size changes.
  18946. @param component the component that was moved or resized
  18947. @param wasMoved true if the component's top-left corner has just moved
  18948. @param wasResized true if the component's width or height has just changed
  18949. @see Component::setBounds, Component::resized, Component::moved
  18950. */
  18951. virtual void componentMovedOrResized (Component& component,
  18952. bool wasMoved,
  18953. bool wasResized);
  18954. /** Called when the component is brought to the top of the z-order.
  18955. @param component the component that was moved
  18956. @see Component::toFront, Component::broughtToFront
  18957. */
  18958. virtual void componentBroughtToFront (Component& component);
  18959. /** Called when the component is made visible or invisible.
  18960. @param component the component that changed
  18961. @see Component::setVisible
  18962. */
  18963. virtual void componentVisibilityChanged (Component& component);
  18964. /** Called when the component has children added or removed.
  18965. @param component the component whose children were changed
  18966. @see Component::childrenChanged, Component::addChildComponent,
  18967. Component::removeChildComponent
  18968. */
  18969. virtual void componentChildrenChanged (Component& component);
  18970. /** Called to indicate that the component's parents have changed.
  18971. When a component is added or removed from its parent, all of its children
  18972. will produce this notification (recursively - so all children of its
  18973. children will also be called as well).
  18974. @param component the component that this listener is registered with
  18975. @see Component::parentHierarchyChanged
  18976. */
  18977. virtual void componentParentHierarchyChanged (Component& component);
  18978. /** Called when the component's name is changed.
  18979. @see Component::setName, Component::getName
  18980. */
  18981. virtual void componentNameChanged (Component& component);
  18982. /** Called when the component is in the process of being deleted.
  18983. This callback is made from inside the destructor, so be very, very cautious
  18984. about what you do in here.
  18985. In particular, bear in mind that it's the Component base class's destructor that calls
  18986. this - so if the object that's being deleted is a subclass of Component, then the
  18987. subclass layers of the object will already have been destructed when it gets to this
  18988. point!
  18989. */
  18990. virtual void componentBeingDeleted (Component& component);
  18991. };
  18992. #endif // __JUCE_COMPONENTLISTENER_JUCEHEADER__
  18993. /*** End of inlined file: juce_ComponentListener.h ***/
  18994. /*** Start of inlined file: juce_KeyListener.h ***/
  18995. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  18996. #define __JUCE_KEYLISTENER_JUCEHEADER__
  18997. /*** Start of inlined file: juce_KeyPress.h ***/
  18998. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  18999. #define __JUCE_KEYPRESS_JUCEHEADER__
  19000. /**
  19001. Represents a key press, including any modifier keys that are needed.
  19002. E.g. a KeyPress might represent CTRL+C, SHIFT+ALT+H, Spacebar, Escape, etc.
  19003. @see Component, KeyListener, Button::addShortcut, KeyPressMappingManager
  19004. */
  19005. class JUCE_API KeyPress
  19006. {
  19007. public:
  19008. /** Creates an (invalid) KeyPress.
  19009. @see isValid
  19010. */
  19011. KeyPress() noexcept;
  19012. /** Creates a KeyPress for a key and some modifiers.
  19013. e.g.
  19014. CTRL+C would be: KeyPress ('c', ModifierKeys::ctrlModifier)
  19015. SHIFT+Escape would be: KeyPress (KeyPress::escapeKey, ModifierKeys::shiftModifier)
  19016. @param keyCode a code that represents the key - this value must be
  19017. one of special constants listed in this class, or an
  19018. 8-bit character code such as a letter (case is ignored),
  19019. digit or a simple key like "," or ".". Note that this
  19020. isn't the same as the textCharacter parameter, so for example
  19021. a keyCode of 'a' and a shift-key modifier should have a
  19022. textCharacter value of 'A'.
  19023. @param modifiers the modifiers to associate with the keystroke
  19024. @param textCharacter the character that would be printed if someone typed
  19025. this keypress into a text editor. This value may be
  19026. null if the keypress is a non-printing character
  19027. @see getKeyCode, isKeyCode, getModifiers
  19028. */
  19029. KeyPress (int keyCode,
  19030. const ModifierKeys& modifiers,
  19031. juce_wchar textCharacter) noexcept;
  19032. /** Creates a keypress with a keyCode but no modifiers or text character.
  19033. */
  19034. KeyPress (int keyCode) noexcept;
  19035. /** Creates a copy of another KeyPress. */
  19036. KeyPress (const KeyPress& other) noexcept;
  19037. /** Copies this KeyPress from another one. */
  19038. KeyPress& operator= (const KeyPress& other) noexcept;
  19039. /** Compares two KeyPress objects. */
  19040. bool operator== (const KeyPress& other) const noexcept;
  19041. /** Compares two KeyPress objects. */
  19042. bool operator!= (const KeyPress& other) const noexcept;
  19043. /** Returns true if this is a valid KeyPress.
  19044. A null keypress can be created by the default constructor, in case it's
  19045. needed.
  19046. */
  19047. bool isValid() const noexcept { return keyCode != 0; }
  19048. /** Returns the key code itself.
  19049. This will either be one of the special constants defined in this class,
  19050. or an 8-bit character code.
  19051. */
  19052. int getKeyCode() const noexcept { return keyCode; }
  19053. /** Returns the key modifiers.
  19054. @see ModifierKeys
  19055. */
  19056. const ModifierKeys getModifiers() const noexcept { return mods; }
  19057. /** Returns the character that is associated with this keypress.
  19058. This is the character that you'd expect to see printed if you press this
  19059. keypress in a text editor or similar component.
  19060. */
  19061. juce_wchar getTextCharacter() const noexcept { return textCharacter; }
  19062. /** Checks whether the KeyPress's key is the same as the one provided, without checking
  19063. the modifiers.
  19064. The values for key codes can either be one of the special constants defined in
  19065. this class, or an 8-bit character code.
  19066. @see getKeyCode
  19067. */
  19068. bool isKeyCode (int keyCodeToCompare) const noexcept { return keyCode == keyCodeToCompare; }
  19069. /** Converts a textual key description to a KeyPress.
  19070. This attempts to decode a textual version of a keypress, e.g. "CTRL + C" or "SPACE".
  19071. This isn't designed to cope with any kind of input, but should be given the
  19072. strings that are created by the getTextDescription() method.
  19073. If the string can't be parsed, the object returned will be invalid.
  19074. @see getTextDescription
  19075. */
  19076. static const KeyPress createFromDescription (const String& textVersion);
  19077. /** Creates a textual description of the key combination.
  19078. e.g. "CTRL + C" or "DELETE".
  19079. To store a keypress in a file, use this method, along with createFromDescription()
  19080. to retrieve it later.
  19081. */
  19082. String getTextDescription() const;
  19083. /** Creates a textual description of the key combination, using unicode icon symbols if possible.
  19084. On OSX, this uses the Apple symbols for command, option, shift, etc, instead of the textual
  19085. modifier key descriptions that are returned by getTextDescription()
  19086. */
  19087. String getTextDescriptionWithIcons() const;
  19088. /** Checks whether the user is currently holding down the keys that make up this
  19089. KeyPress.
  19090. Note that this will return false if any extra modifier keys are
  19091. down - e.g. if the keypress is CTRL+X and the user is actually holding CTRL+ALT+x
  19092. then it will be false.
  19093. */
  19094. bool isCurrentlyDown() const;
  19095. /** Checks whether a particular key is held down, irrespective of modifiers.
  19096. The values for key codes can either be one of the special constants defined in
  19097. this class, or an 8-bit character code.
  19098. */
  19099. static bool isKeyCurrentlyDown (int keyCode);
  19100. // Key codes
  19101. //
  19102. // Note that the actual values of these are platform-specific and may change
  19103. // without warning, so don't store them anywhere as constants. For persisting/retrieving
  19104. // KeyPress objects, use getTextDescription() and createFromDescription() instead.
  19105. //
  19106. static const int spaceKey; /**< key-code for the space bar */
  19107. static const int escapeKey; /**< key-code for the escape key */
  19108. static const int returnKey; /**< key-code for the return key*/
  19109. static const int tabKey; /**< key-code for the tab key*/
  19110. static const int deleteKey; /**< key-code for the delete key (not backspace) */
  19111. static const int backspaceKey; /**< key-code for the backspace key */
  19112. static const int insertKey; /**< key-code for the insert key */
  19113. static const int upKey; /**< key-code for the cursor-up key */
  19114. static const int downKey; /**< key-code for the cursor-down key */
  19115. static const int leftKey; /**< key-code for the cursor-left key */
  19116. static const int rightKey; /**< key-code for the cursor-right key */
  19117. static const int pageUpKey; /**< key-code for the page-up key */
  19118. static const int pageDownKey; /**< key-code for the page-down key */
  19119. static const int homeKey; /**< key-code for the home key */
  19120. static const int endKey; /**< key-code for the end key */
  19121. static const int F1Key; /**< key-code for the F1 key */
  19122. static const int F2Key; /**< key-code for the F2 key */
  19123. static const int F3Key; /**< key-code for the F3 key */
  19124. static const int F4Key; /**< key-code for the F4 key */
  19125. static const int F5Key; /**< key-code for the F5 key */
  19126. static const int F6Key; /**< key-code for the F6 key */
  19127. static const int F7Key; /**< key-code for the F7 key */
  19128. static const int F8Key; /**< key-code for the F8 key */
  19129. static const int F9Key; /**< key-code for the F9 key */
  19130. static const int F10Key; /**< key-code for the F10 key */
  19131. static const int F11Key; /**< key-code for the F11 key */
  19132. static const int F12Key; /**< key-code for the F12 key */
  19133. static const int F13Key; /**< key-code for the F13 key */
  19134. static const int F14Key; /**< key-code for the F14 key */
  19135. static const int F15Key; /**< key-code for the F15 key */
  19136. static const int F16Key; /**< key-code for the F16 key */
  19137. static const int numberPad0; /**< key-code for the 0 on the numeric keypad. */
  19138. static const int numberPad1; /**< key-code for the 1 on the numeric keypad. */
  19139. static const int numberPad2; /**< key-code for the 2 on the numeric keypad. */
  19140. static const int numberPad3; /**< key-code for the 3 on the numeric keypad. */
  19141. static const int numberPad4; /**< key-code for the 4 on the numeric keypad. */
  19142. static const int numberPad5; /**< key-code for the 5 on the numeric keypad. */
  19143. static const int numberPad6; /**< key-code for the 6 on the numeric keypad. */
  19144. static const int numberPad7; /**< key-code for the 7 on the numeric keypad. */
  19145. static const int numberPad8; /**< key-code for the 8 on the numeric keypad. */
  19146. static const int numberPad9; /**< key-code for the 9 on the numeric keypad. */
  19147. static const int numberPadAdd; /**< key-code for the add sign on the numeric keypad. */
  19148. static const int numberPadSubtract; /**< key-code for the subtract sign on the numeric keypad. */
  19149. static const int numberPadMultiply; /**< key-code for the multiply sign on the numeric keypad. */
  19150. static const int numberPadDivide; /**< key-code for the divide sign on the numeric keypad. */
  19151. static const int numberPadSeparator; /**< key-code for the comma on the numeric keypad. */
  19152. static const int numberPadDecimalPoint; /**< key-code for the decimal point sign on the numeric keypad. */
  19153. static const int numberPadEquals; /**< key-code for the equals key on the numeric keypad. */
  19154. static const int numberPadDelete; /**< key-code for the delete key on the numeric keypad. */
  19155. static const int playKey; /**< key-code for a multimedia 'play' key, (not all keyboards will have one) */
  19156. static const int stopKey; /**< key-code for a multimedia 'stop' key, (not all keyboards will have one) */
  19157. static const int fastForwardKey; /**< key-code for a multimedia 'fast-forward' key, (not all keyboards will have one) */
  19158. static const int rewindKey; /**< key-code for a multimedia 'rewind' key, (not all keyboards will have one) */
  19159. private:
  19160. int keyCode;
  19161. ModifierKeys mods;
  19162. juce_wchar textCharacter;
  19163. JUCE_LEAK_DETECTOR (KeyPress);
  19164. };
  19165. #endif // __JUCE_KEYPRESS_JUCEHEADER__
  19166. /*** End of inlined file: juce_KeyPress.h ***/
  19167. class Component;
  19168. /**
  19169. Receives callbacks when keys are pressed.
  19170. You can add a key listener to a component to be informed when that component
  19171. gets key events. See the Component::addListener method for more details.
  19172. @see KeyPress, Component::addKeyListener, KeyPressMappingManager
  19173. */
  19174. class JUCE_API KeyListener
  19175. {
  19176. public:
  19177. /** Destructor. */
  19178. virtual ~KeyListener() {}
  19179. /** Called to indicate that a key has been pressed.
  19180. If your implementation returns true, then the key event is considered to have
  19181. been consumed, and will not be passed on to any other components. If it returns
  19182. false, then the key will be passed to other components that might want to use it.
  19183. @param key the keystroke, including modifier keys
  19184. @param originatingComponent the component that received the key event
  19185. @see keyStateChanged, Component::keyPressed
  19186. */
  19187. virtual bool keyPressed (const KeyPress& key,
  19188. Component* originatingComponent) = 0;
  19189. /** Called when any key is pressed or released.
  19190. When this is called, classes that might be interested in
  19191. the state of one or more keys can use KeyPress::isKeyCurrentlyDown() to
  19192. check whether their key has changed.
  19193. If your implementation returns true, then the key event is considered to have
  19194. been consumed, and will not be passed on to any other components. If it returns
  19195. false, then the key will be passed to other components that might want to use it.
  19196. @param originatingComponent the component that received the key event
  19197. @param isKeyDown true if a key is being pressed, false if one is being released
  19198. @see KeyPress, Component::keyStateChanged
  19199. */
  19200. virtual bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  19201. };
  19202. #endif // __JUCE_KEYLISTENER_JUCEHEADER__
  19203. /*** End of inlined file: juce_KeyListener.h ***/
  19204. /*** Start of inlined file: juce_KeyboardFocusTraverser.h ***/
  19205. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  19206. #define __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  19207. class Component;
  19208. /**
  19209. Controls the order in which focus moves between components.
  19210. The default algorithm used by this class to work out the order of traversal
  19211. is as follows:
  19212. - if two components both have an explicit focus order specified, then the
  19213. one with the lowest number comes first (see the Component::setExplicitFocusOrder()
  19214. method).
  19215. - any component with an explicit focus order greater than 0 comes before ones
  19216. that don't have an order specified.
  19217. - any unspecified components are traversed in a left-to-right, then top-to-bottom
  19218. order.
  19219. If you need traversal in a more customised way, you can create a subclass
  19220. of KeyboardFocusTraverser that uses your own algorithm, and use
  19221. Component::createFocusTraverser() to create it.
  19222. @see Component::setExplicitFocusOrder, Component::createFocusTraverser
  19223. */
  19224. class JUCE_API KeyboardFocusTraverser
  19225. {
  19226. public:
  19227. KeyboardFocusTraverser();
  19228. /** Destructor. */
  19229. virtual ~KeyboardFocusTraverser();
  19230. /** Returns the component that should be given focus after the specified one
  19231. when moving "forwards".
  19232. The default implementation will return the next component which is to the
  19233. right of or below this one.
  19234. This may return 0 if there's no suitable candidate.
  19235. */
  19236. virtual Component* getNextComponent (Component* current);
  19237. /** Returns the component that should be given focus after the specified one
  19238. when moving "backwards".
  19239. The default implementation will return the next component which is to the
  19240. left of or above this one.
  19241. This may return 0 if there's no suitable candidate.
  19242. */
  19243. virtual Component* getPreviousComponent (Component* current);
  19244. /** Returns the component that should receive focus be default within the given
  19245. parent component.
  19246. The default implementation will just return the foremost child component that
  19247. wants focus.
  19248. This may return 0 if there's no suitable candidate.
  19249. */
  19250. virtual Component* getDefaultComponent (Component* parentComponent);
  19251. };
  19252. #endif // __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  19253. /*** End of inlined file: juce_KeyboardFocusTraverser.h ***/
  19254. /*** Start of inlined file: juce_ImageEffectFilter.h ***/
  19255. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  19256. #define __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  19257. /*** Start of inlined file: juce_Graphics.h ***/
  19258. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  19259. #define __JUCE_GRAPHICS_JUCEHEADER__
  19260. /*** Start of inlined file: juce_Font.h ***/
  19261. #ifndef __JUCE_FONT_JUCEHEADER__
  19262. #define __JUCE_FONT_JUCEHEADER__
  19263. /*** Start of inlined file: juce_Typeface.h ***/
  19264. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  19265. #define __JUCE_TYPEFACE_JUCEHEADER__
  19266. class Path;
  19267. class Font;
  19268. class EdgeTable;
  19269. class AffineTransform;
  19270. /**
  19271. A typeface represents a size-independent font.
  19272. This base class is abstract, but calling createSystemTypefaceFor() will return
  19273. a platform-specific subclass that can be used.
  19274. The CustomTypeface subclass allow you to build your own typeface, and to
  19275. load and save it in the Juce typeface format.
  19276. Normally you should never need to deal directly with Typeface objects - the Font
  19277. class does everything you typically need for rendering text.
  19278. @see CustomTypeface, Font
  19279. */
  19280. class JUCE_API Typeface : public SingleThreadedReferenceCountedObject
  19281. {
  19282. public:
  19283. /** A handy typedef for a pointer to a typeface. */
  19284. typedef ReferenceCountedObjectPtr <Typeface> Ptr;
  19285. /** Returns the name of the typeface.
  19286. @see Font::getTypefaceName
  19287. */
  19288. const String& getName() const noexcept { return name; }
  19289. /** Creates a new system typeface. */
  19290. static Ptr createSystemTypefaceFor (const Font& font);
  19291. /** Destructor. */
  19292. virtual ~Typeface();
  19293. /** Returns true if this typeface can be used to render the specified font.
  19294. When called, the font will already have been checked to make sure that its name and
  19295. style flags match the typeface.
  19296. */
  19297. virtual bool isSuitableForFont (const Font&) const { return true; }
  19298. /** Returns the ascent of the font, as a proportion of its height.
  19299. The height is considered to always be normalised as 1.0, so this will be a
  19300. value less that 1.0, indicating the proportion of the font that lies above
  19301. its baseline.
  19302. */
  19303. virtual float getAscent() const = 0;
  19304. /** Returns the descent of the font, as a proportion of its height.
  19305. The height is considered to always be normalised as 1.0, so this will be a
  19306. value less that 1.0, indicating the proportion of the font that lies below
  19307. its baseline.
  19308. */
  19309. virtual float getDescent() const = 0;
  19310. /** Measures the width of a line of text.
  19311. The distance returned is based on the font having an normalised height of 1.0.
  19312. You should never need to call this directly! Use Font::getStringWidth() instead!
  19313. */
  19314. virtual float getStringWidth (const String& text) = 0;
  19315. /** Converts a line of text into its glyph numbers and their positions.
  19316. The distances returned are based on the font having an normalised height of 1.0.
  19317. You should never need to call this directly! Use Font::getGlyphPositions() instead!
  19318. */
  19319. virtual void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets) = 0;
  19320. /** Returns the outline for a glyph.
  19321. The path returned will be normalised to a font height of 1.0.
  19322. */
  19323. virtual bool getOutlineForGlyph (int glyphNumber, Path& path) = 0;
  19324. /** Returns a new EdgeTable that contains the path for the givem glyph, with the specified transform applied. */
  19325. virtual EdgeTable* getEdgeTableForGlyph (int glyphNumber, const AffineTransform& transform);
  19326. /** Returns true if the typeface uses hinting. */
  19327. virtual bool isHinted() const { return false; }
  19328. /** Changes the number of fonts that are cached in memory. */
  19329. static void setTypefaceCacheSize (int numFontsToCache);
  19330. protected:
  19331. String name;
  19332. explicit Typeface (const String& name) noexcept;
  19333. static Ptr getFallbackTypeface();
  19334. private:
  19335. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Typeface);
  19336. };
  19337. #endif // __JUCE_TYPEFACE_JUCEHEADER__
  19338. /*** End of inlined file: juce_Typeface.h ***/
  19339. class LowLevelGraphicsContext;
  19340. /**
  19341. Represents a particular font, including its size, style, etc.
  19342. Apart from the typeface to be used, a Font object also dictates whether
  19343. the font is bold, italic, underlined, how big it is, and its kerning and
  19344. horizontal scale factor.
  19345. @see Typeface
  19346. */
  19347. class JUCE_API Font
  19348. {
  19349. public:
  19350. /** A combination of these values is used by the constructor to specify the
  19351. style of font to use.
  19352. */
  19353. enum FontStyleFlags
  19354. {
  19355. plain = 0, /**< indicates a plain, non-bold, non-italic version of the font. @see setStyleFlags */
  19356. bold = 1, /**< boldens the font. @see setStyleFlags */
  19357. italic = 2, /**< finds an italic version of the font. @see setStyleFlags */
  19358. underlined = 4 /**< underlines the font. @see setStyleFlags */
  19359. };
  19360. /** Creates a sans-serif font in a given size.
  19361. @param fontHeight the height in pixels (can be fractional)
  19362. @param styleFlags the style to use - this can be a combination of the
  19363. Font::bold, Font::italic and Font::underlined, or
  19364. just Font::plain for the normal style.
  19365. @see FontStyleFlags, getDefaultSansSerifFontName
  19366. */
  19367. Font (float fontHeight, int styleFlags = plain);
  19368. /** Creates a font with a given typeface and parameters.
  19369. @param typefaceName the name of the typeface to use
  19370. @param fontHeight the height in pixels (can be fractional)
  19371. @param styleFlags the style to use - this can be a combination of the
  19372. Font::bold, Font::italic and Font::underlined, or
  19373. just Font::plain for the normal style.
  19374. @see FontStyleFlags, getDefaultSansSerifFontName
  19375. */
  19376. Font (const String& typefaceName, float fontHeight, int styleFlags);
  19377. /** Creates a copy of another Font object. */
  19378. Font (const Font& other) noexcept;
  19379. /** Creates a font for a typeface. */
  19380. Font (const Typeface::Ptr& typeface);
  19381. /** Creates a basic sans-serif font at a default height.
  19382. You should use one of the other constructors for creating a font that you're planning
  19383. on drawing with - this constructor is here to help initialise objects before changing
  19384. the font's settings later.
  19385. */
  19386. Font();
  19387. /** Copies this font from another one. */
  19388. Font& operator= (const Font& other) noexcept;
  19389. bool operator== (const Font& other) const noexcept;
  19390. bool operator!= (const Font& other) const noexcept;
  19391. /** Destructor. */
  19392. ~Font() noexcept;
  19393. /** Changes the name of the typeface family.
  19394. e.g. "Arial", "Courier", etc.
  19395. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  19396. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  19397. but are generic names that are used to represent the various default fonts.
  19398. If you need to know the exact typeface name being used, you can call
  19399. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  19400. If a suitable font isn't found on the machine, it'll just use a default instead.
  19401. */
  19402. void setTypefaceName (const String& faceName);
  19403. /** Returns the name of the typeface family that this font uses.
  19404. e.g. "Arial", "Courier", etc.
  19405. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  19406. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  19407. but are generic names that are used to represent the various default fonts.
  19408. If you need to know the exact typeface name being used, you can call
  19409. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  19410. */
  19411. const String& getTypefaceName() const noexcept { return font->typefaceName; }
  19412. /** Returns a typeface name that represents the default sans-serif font.
  19413. This is also the typeface that will be used when a font is created without
  19414. specifying any typeface details.
  19415. Note that this method just returns a generic placeholder string that means "the default
  19416. sans-serif font" - it's not the actual name of this font. To get the actual name, use
  19417. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  19418. @see setTypefaceName, getDefaultSerifFontName, getDefaultMonospacedFontName
  19419. */
  19420. static const String& getDefaultSansSerifFontName();
  19421. /** Returns a typeface name that represents the default sans-serif font.
  19422. Note that this method just returns a generic placeholder string that means "the default
  19423. serif font" - it's not the actual name of this font. To get the actual name, use
  19424. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  19425. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultMonospacedFontName
  19426. */
  19427. static const String& getDefaultSerifFontName();
  19428. /** Returns a typeface name that represents the default sans-serif font.
  19429. Note that this method just returns a generic placeholder string that means "the default
  19430. monospaced font" - it's not the actual name of this font. To get the actual name, use
  19431. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  19432. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultSerifFontName
  19433. */
  19434. static const String& getDefaultMonospacedFontName();
  19435. /** Returns the typeface names of the default fonts on the current platform. */
  19436. static void getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback);
  19437. /** Returns the total height of this font.
  19438. This is the maximum height, from the top of the ascent to the bottom of the
  19439. descenders.
  19440. @see setHeight, setHeightWithoutChangingWidth, getAscent
  19441. */
  19442. float getHeight() const noexcept { return font->height; }
  19443. /** Changes the font's height.
  19444. @see getHeight, setHeightWithoutChangingWidth
  19445. */
  19446. void setHeight (float newHeight);
  19447. /** Changes the font's height without changing its width.
  19448. This alters the horizontal scale to compensate for the change in height.
  19449. */
  19450. void setHeightWithoutChangingWidth (float newHeight);
  19451. /** Returns the height of the font above its baseline.
  19452. This is the maximum height from the baseline to the top.
  19453. @see getHeight, getDescent
  19454. */
  19455. float getAscent() const;
  19456. /** Returns the amount that the font descends below its baseline.
  19457. This is calculated as (getHeight() - getAscent()).
  19458. @see getAscent, getHeight
  19459. */
  19460. float getDescent() const;
  19461. /** Returns the font's style flags.
  19462. This will return a bitwise-or'ed combination of values from the FontStyleFlags
  19463. enum, to describe whether the font is bold, italic, etc.
  19464. @see FontStyleFlags
  19465. */
  19466. int getStyleFlags() const noexcept { return font->styleFlags; }
  19467. /** Changes the font's style.
  19468. @param newFlags a bitwise-or'ed combination of values from the FontStyleFlags
  19469. enum, to set the font's properties
  19470. @see FontStyleFlags
  19471. */
  19472. void setStyleFlags (int newFlags);
  19473. /** Makes the font bold or non-bold. */
  19474. void setBold (bool shouldBeBold);
  19475. /** Returns a copy of this font with the bold attribute set. */
  19476. Font boldened() const;
  19477. /** Returns true if the font is bold. */
  19478. bool isBold() const noexcept;
  19479. /** Makes the font italic or non-italic. */
  19480. void setItalic (bool shouldBeItalic);
  19481. /** Returns a copy of this font with the italic attribute set. */
  19482. Font italicised() const;
  19483. /** Returns true if the font is italic. */
  19484. bool isItalic() const noexcept;
  19485. /** Makes the font underlined or non-underlined. */
  19486. void setUnderline (bool shouldBeUnderlined);
  19487. /** Returns true if the font is underlined. */
  19488. bool isUnderlined() const noexcept;
  19489. /** Changes the font's horizontal scale factor.
  19490. @param scaleFactor a value of 1.0 is the normal scale, less than this will be
  19491. narrower, greater than 1.0 will be stretched out.
  19492. */
  19493. void setHorizontalScale (float scaleFactor);
  19494. /** Returns the font's horizontal scale.
  19495. A value of 1.0 is the normal scale, less than this will be narrower, greater
  19496. than 1.0 will be stretched out.
  19497. @see setHorizontalScale
  19498. */
  19499. float getHorizontalScale() const noexcept { return font->horizontalScale; }
  19500. /** Changes the font's kerning.
  19501. @param extraKerning a multiple of the font's height that will be added
  19502. to space between the characters. So a value of zero is
  19503. normal spacing, positive values spread the letters out,
  19504. negative values make them closer together.
  19505. */
  19506. void setExtraKerningFactor (float extraKerning);
  19507. /** Returns the font's kerning.
  19508. This is the extra space added between adjacent characters, as a proportion
  19509. of the font's height.
  19510. A value of zero is normal spacing, positive values will spread the letters
  19511. out more, and negative values make them closer together.
  19512. */
  19513. float getExtraKerningFactor() const noexcept { return font->kerning; }
  19514. /** Changes all the font's characteristics with one call. */
  19515. void setSizeAndStyle (float newHeight,
  19516. int newStyleFlags,
  19517. float newHorizontalScale,
  19518. float newKerningAmount);
  19519. /** Returns the total width of a string as it would be drawn using this font.
  19520. For a more accurate floating-point result, use getStringWidthFloat().
  19521. */
  19522. int getStringWidth (const String& text) const;
  19523. /** Returns the total width of a string as it would be drawn using this font.
  19524. @see getStringWidth
  19525. */
  19526. float getStringWidthFloat (const String& text) const;
  19527. /** Returns the series of glyph numbers and their x offsets needed to represent a string.
  19528. An extra x offset is added at the end of the run, to indicate where the right hand
  19529. edge of the last character is.
  19530. */
  19531. void getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const;
  19532. /** Returns the typeface used by this font.
  19533. Note that the object returned may go out of scope if this font is deleted
  19534. or has its style changed.
  19535. */
  19536. Typeface* getTypeface() const;
  19537. /** Creates an array of Font objects to represent all the fonts on the system.
  19538. If you just need the names of the typefaces, you can also use
  19539. findAllTypefaceNames() instead.
  19540. @param results the array to which new Font objects will be added.
  19541. */
  19542. static void findFonts (Array<Font>& results);
  19543. /** Returns a list of all the available typeface names.
  19544. The names returned can be passed into setTypefaceName().
  19545. You can use this instead of findFonts() if you only need their names, and not
  19546. font objects.
  19547. */
  19548. static StringArray findAllTypefaceNames();
  19549. /** Returns the name of the typeface to be used for rendering glyphs that aren't found
  19550. in the requested typeface.
  19551. */
  19552. static const String& getFallbackFontName();
  19553. /** Sets the (platform-specific) name of the typeface to use to find glyphs that aren't
  19554. available in whatever font you're trying to use.
  19555. */
  19556. static void setFallbackFontName (const String& name);
  19557. /** Creates a string to describe this font.
  19558. The string will contain information to describe the font's typeface, size, and
  19559. style. To recreate the font from this string, use fromString().
  19560. */
  19561. String toString() const;
  19562. /** Recreates a font from its stringified encoding.
  19563. This method takes a string that was created by toString(), and recreates the
  19564. original font.
  19565. */
  19566. static Font fromString (const String& fontDescription);
  19567. private:
  19568. friend class FontGlyphAlphaMap;
  19569. friend class TypefaceCache;
  19570. class SharedFontInternal : public SingleThreadedReferenceCountedObject
  19571. {
  19572. public:
  19573. SharedFontInternal (float height, int styleFlags) noexcept;
  19574. SharedFontInternal (const String& typefaceName, float height, int styleFlags) noexcept;
  19575. SharedFontInternal (const Typeface::Ptr& typeface) noexcept;
  19576. SharedFontInternal (const SharedFontInternal& other) noexcept;
  19577. bool operator== (const SharedFontInternal&) const noexcept;
  19578. String typefaceName;
  19579. float height, horizontalScale, kerning, ascent;
  19580. int styleFlags;
  19581. Typeface::Ptr typeface;
  19582. };
  19583. ReferenceCountedObjectPtr <SharedFontInternal> font;
  19584. void dupeInternalIfShared();
  19585. JUCE_LEAK_DETECTOR (Font);
  19586. };
  19587. #endif // __JUCE_FONT_JUCEHEADER__
  19588. /*** End of inlined file: juce_Font.h ***/
  19589. /*** Start of inlined file: juce_Rectangle.h ***/
  19590. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  19591. #define __JUCE_RECTANGLE_JUCEHEADER__
  19592. class RectangleList;
  19593. /**
  19594. Manages a rectangle and allows geometric operations to be performed on it.
  19595. @see RectangleList, Path, Line, Point
  19596. */
  19597. template <typename ValueType>
  19598. class Rectangle
  19599. {
  19600. public:
  19601. /** Creates a rectangle of zero size.
  19602. The default co-ordinates will be (0, 0, 0, 0).
  19603. */
  19604. Rectangle() noexcept
  19605. : x(), y(), w(), h()
  19606. {
  19607. }
  19608. /** Creates a copy of another rectangle. */
  19609. Rectangle (const Rectangle& other) noexcept
  19610. : x (other.x), y (other.y),
  19611. w (other.w), h (other.h)
  19612. {
  19613. }
  19614. /** Creates a rectangle with a given position and size. */
  19615. Rectangle (const ValueType initialX, const ValueType initialY,
  19616. const ValueType width, const ValueType height) noexcept
  19617. : x (initialX), y (initialY),
  19618. w (width), h (height)
  19619. {
  19620. }
  19621. /** Creates a rectangle with a given size, and a position of (0, 0). */
  19622. Rectangle (const ValueType width, const ValueType height) noexcept
  19623. : x(), y(), w (width), h (height)
  19624. {
  19625. }
  19626. /** Creates a Rectangle from the positions of two opposite corners. */
  19627. Rectangle (const Point<ValueType>& corner1, const Point<ValueType>& corner2) noexcept
  19628. : x (jmin (corner1.getX(), corner2.getX())),
  19629. y (jmin (corner1.getY(), corner2.getY())),
  19630. w (corner1.getX() - corner2.getX()),
  19631. h (corner1.getY() - corner2.getY())
  19632. {
  19633. if (w < ValueType()) w = -w;
  19634. if (h < ValueType()) h = -h;
  19635. }
  19636. /** Creates a Rectangle from a set of left, right, top, bottom coordinates.
  19637. The right and bottom values must be larger than the left and top ones, or the resulting
  19638. rectangle will have a negative size.
  19639. */
  19640. static Rectangle leftTopRightBottom (const ValueType left, const ValueType top,
  19641. const ValueType right, const ValueType bottom) noexcept
  19642. {
  19643. return Rectangle (left, top, right - left, bottom - top);
  19644. }
  19645. Rectangle& operator= (const Rectangle& other) noexcept
  19646. {
  19647. x = other.x; y = other.y;
  19648. w = other.w; h = other.h;
  19649. return *this;
  19650. }
  19651. /** Destructor. */
  19652. ~Rectangle() noexcept {}
  19653. /** Returns true if the rectangle's width and height are both zero or less */
  19654. bool isEmpty() const noexcept { return w <= ValueType() || h <= ValueType(); }
  19655. /** Returns the x co-ordinate of the rectangle's left-hand-side. */
  19656. inline ValueType getX() const noexcept { return x; }
  19657. /** Returns the y co-ordinate of the rectangle's top edge. */
  19658. inline ValueType getY() const noexcept { return y; }
  19659. /** Returns the width of the rectangle. */
  19660. inline ValueType getWidth() const noexcept { return w; }
  19661. /** Returns the height of the rectangle. */
  19662. inline ValueType getHeight() const noexcept { return h; }
  19663. /** Returns the x co-ordinate of the rectangle's right-hand-side. */
  19664. inline ValueType getRight() const noexcept { return x + w; }
  19665. /** Returns the y co-ordinate of the rectangle's bottom edge. */
  19666. inline ValueType getBottom() const noexcept { return y + h; }
  19667. /** Returns the x co-ordinate of the rectangle's centre. */
  19668. ValueType getCentreX() const noexcept { return x + w / (ValueType) 2; }
  19669. /** Returns the y co-ordinate of the rectangle's centre. */
  19670. ValueType getCentreY() const noexcept { return y + h / (ValueType) 2; }
  19671. /** Returns the centre point of the rectangle. */
  19672. Point<ValueType> getCentre() const noexcept { return Point<ValueType> (x + w / (ValueType) 2, y + h / (ValueType) 2); }
  19673. /** Returns the aspect ratio of the rectangle's width / height.
  19674. If widthOverHeight is true, it returns width / height; if widthOverHeight is false,
  19675. it returns height / width. */
  19676. ValueType getAspectRatio (const bool widthOverHeight = true) const noexcept { return widthOverHeight ? w / h : h / w; }
  19677. /** Returns the rectangle's top-left position as a Point. */
  19678. Point<ValueType> getPosition() const noexcept { return Point<ValueType> (x, y); }
  19679. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  19680. void setPosition (const Point<ValueType>& newPos) noexcept { x = newPos.getX(); y = newPos.getY(); }
  19681. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  19682. void setPosition (const ValueType newX, const ValueType newY) noexcept { x = newX; y = newY; }
  19683. /** Returns a rectangle with the same size as this one, but a new position. */
  19684. Rectangle withPosition (const ValueType newX, const ValueType newY) const noexcept { return Rectangle (newX, newY, w, h); }
  19685. /** Returns a rectangle with the same size as this one, but a new position. */
  19686. Rectangle withPosition (const Point<ValueType>& newPos) const noexcept { return Rectangle (newPos.getX(), newPos.getY(), w, h); }
  19687. /** Returns the rectangle's top-left position as a Point. */
  19688. Point<ValueType> getTopLeft() const noexcept { return getPosition(); }
  19689. /** Returns the rectangle's top-right position as a Point. */
  19690. Point<ValueType> getTopRight() const noexcept { return Point<ValueType> (x + w, y); }
  19691. /** Returns the rectangle's bottom-left position as a Point. */
  19692. Point<ValueType> getBottomLeft() const noexcept { return Point<ValueType> (x, y + h); }
  19693. /** Returns the rectangle's bottom-right position as a Point. */
  19694. Point<ValueType> getBottomRight() const noexcept { return Point<ValueType> (x + w, y + h); }
  19695. /** Changes the rectangle's size, leaving the position of its top-left corner unchanged. */
  19696. void setSize (const ValueType newWidth, const ValueType newHeight) noexcept { w = newWidth; h = newHeight; }
  19697. /** Returns a rectangle with the same position as this one, but a new size. */
  19698. Rectangle withSize (const ValueType newWidth, const ValueType newHeight) const noexcept { return Rectangle (x, y, newWidth, newHeight); }
  19699. /** Changes all the rectangle's co-ordinates. */
  19700. void setBounds (const ValueType newX, const ValueType newY,
  19701. const ValueType newWidth, const ValueType newHeight) noexcept
  19702. {
  19703. x = newX; y = newY; w = newWidth; h = newHeight;
  19704. }
  19705. /** Changes the rectangle's X coordinate */
  19706. void setX (const ValueType newX) noexcept { x = newX; }
  19707. /** Changes the rectangle's Y coordinate */
  19708. void setY (const ValueType newY) noexcept { y = newY; }
  19709. /** Changes the rectangle's width */
  19710. void setWidth (const ValueType newWidth) noexcept { w = newWidth; }
  19711. /** Changes the rectangle's height */
  19712. void setHeight (const ValueType newHeight) noexcept { h = newHeight; }
  19713. /** Returns a rectangle which has the same size and y-position as this one, but with a different x-position. */
  19714. Rectangle withX (const ValueType newX) const noexcept { return Rectangle (newX, y, w, h); }
  19715. /** Returns a rectangle which has the same size and x-position as this one, but with a different y-position. */
  19716. Rectangle withY (const ValueType newY) const noexcept { return Rectangle (x, newY, w, h); }
  19717. /** Returns a rectangle which has the same position and height as this one, but with a different width. */
  19718. Rectangle withWidth (const ValueType newWidth) const noexcept { return Rectangle (x, y, newWidth, h); }
  19719. /** Returns a rectangle which has the same position and width as this one, but with a different height. */
  19720. Rectangle withHeight (const ValueType newHeight) const noexcept { return Rectangle (x, y, w, newHeight); }
  19721. /** Moves the x position, adjusting the width so that the right-hand edge remains in the same place.
  19722. If the x is moved to be on the right of the current right-hand edge, the width will be set to zero.
  19723. @see withLeft
  19724. */
  19725. void setLeft (const ValueType newLeft) noexcept
  19726. {
  19727. w = jmax (ValueType(), x + w - newLeft);
  19728. x = newLeft;
  19729. }
  19730. /** Returns a new rectangle with a different x position, but the same right-hand edge as this one.
  19731. If the new x is beyond the right of the current right-hand edge, the width will be set to zero.
  19732. @see setLeft
  19733. */
  19734. Rectangle withLeft (const ValueType newLeft) const noexcept { return Rectangle (newLeft, y, jmax (ValueType(), x + w - newLeft), h); }
  19735. /** Moves the y position, adjusting the height so that the bottom edge remains in the same place.
  19736. If the y is moved to be below the current bottom edge, the height will be set to zero.
  19737. @see withTop
  19738. */
  19739. void setTop (const ValueType newTop) noexcept
  19740. {
  19741. h = jmax (ValueType(), y + h - newTop);
  19742. y = newTop;
  19743. }
  19744. /** Returns a new rectangle with a different y position, but the same bottom edge as this one.
  19745. If the new y is beyond the bottom of the current rectangle, the height will be set to zero.
  19746. @see setTop
  19747. */
  19748. Rectangle withTop (const ValueType newTop) const noexcept { return Rectangle (x, newTop, w, jmax (ValueType(), y + h - newTop)); }
  19749. /** Adjusts the width so that the right-hand edge of the rectangle has this new value.
  19750. If the new right is below the current X value, the X will be pushed down to match it.
  19751. @see getRight, withRight
  19752. */
  19753. void setRight (const ValueType newRight) noexcept
  19754. {
  19755. x = jmin (x, newRight);
  19756. w = newRight - x;
  19757. }
  19758. /** Returns a new rectangle with a different right-hand edge position, but the same left-hand edge as this one.
  19759. If the new right edge is below the current left-hand edge, the width will be set to zero.
  19760. @see setRight
  19761. */
  19762. Rectangle withRight (const ValueType newRight) const noexcept { return Rectangle (jmin (x, newRight), y, jmax (ValueType(), newRight - x), h); }
  19763. /** Adjusts the height so that the bottom edge of the rectangle has this new value.
  19764. If the new bottom is lower than the current Y value, the Y will be pushed down to match it.
  19765. @see getBottom, withBottom
  19766. */
  19767. void setBottom (const ValueType newBottom) noexcept
  19768. {
  19769. y = jmin (y, newBottom);
  19770. h = newBottom - y;
  19771. }
  19772. /** Returns a new rectangle with a different bottom edge position, but the same top edge as this one.
  19773. If the new y is beyond the bottom of the current rectangle, the height will be set to zero.
  19774. @see setBottom
  19775. */
  19776. Rectangle withBottom (const ValueType newBottom) const noexcept { return Rectangle (x, jmin (y, newBottom), w, jmax (ValueType(), newBottom - y)); }
  19777. /** Moves the rectangle's position by adding amount to its x and y co-ordinates. */
  19778. void translate (const ValueType deltaX,
  19779. const ValueType deltaY) noexcept
  19780. {
  19781. x += deltaX;
  19782. y += deltaY;
  19783. }
  19784. /** Returns a rectangle which is the same as this one moved by a given amount. */
  19785. Rectangle translated (const ValueType deltaX,
  19786. const ValueType deltaY) const noexcept
  19787. {
  19788. return Rectangle (x + deltaX, y + deltaY, w, h);
  19789. }
  19790. /** Returns a rectangle which is the same as this one moved by a given amount. */
  19791. Rectangle operator+ (const Point<ValueType>& deltaPosition) const noexcept
  19792. {
  19793. return Rectangle (x + deltaPosition.getX(), y + deltaPosition.getY(), w, h);
  19794. }
  19795. /** Moves this rectangle by a given amount. */
  19796. Rectangle& operator+= (const Point<ValueType>& deltaPosition) noexcept
  19797. {
  19798. x += deltaPosition.getX(); y += deltaPosition.getY();
  19799. return *this;
  19800. }
  19801. /** Returns a rectangle which is the same as this one moved by a given amount. */
  19802. Rectangle operator- (const Point<ValueType>& deltaPosition) const noexcept
  19803. {
  19804. return Rectangle (x - deltaPosition.getX(), y - deltaPosition.getY(), w, h);
  19805. }
  19806. /** Moves this rectangle by a given amount. */
  19807. Rectangle& operator-= (const Point<ValueType>& deltaPosition) noexcept
  19808. {
  19809. x -= deltaPosition.getX(); y -= deltaPosition.getY();
  19810. return *this;
  19811. }
  19812. /** Expands the rectangle by a given amount.
  19813. Effectively, its new size is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  19814. @see expanded, reduce, reduced
  19815. */
  19816. void expand (const ValueType deltaX,
  19817. const ValueType deltaY) noexcept
  19818. {
  19819. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  19820. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  19821. setBounds (x - deltaX, y - deltaY, nw, nh);
  19822. }
  19823. /** Returns a rectangle that is larger than this one by a given amount.
  19824. Effectively, the rectangle returned is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  19825. @see expand, reduce, reduced
  19826. */
  19827. Rectangle expanded (const ValueType deltaX,
  19828. const ValueType deltaY) const noexcept
  19829. {
  19830. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  19831. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  19832. return Rectangle (x - deltaX, y - deltaY, nw, nh);
  19833. }
  19834. /** Shrinks the rectangle by a given amount.
  19835. Effectively, its new size is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  19836. @see reduced, expand, expanded
  19837. */
  19838. void reduce (const ValueType deltaX,
  19839. const ValueType deltaY) noexcept
  19840. {
  19841. expand (-deltaX, -deltaY);
  19842. }
  19843. /** Returns a rectangle that is smaller than this one by a given amount.
  19844. Effectively, the rectangle returned is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  19845. @see reduce, expand, expanded
  19846. */
  19847. Rectangle reduced (const ValueType deltaX,
  19848. const ValueType deltaY) const noexcept
  19849. {
  19850. return expanded (-deltaX, -deltaY);
  19851. }
  19852. /** Removes a strip from the top of this rectangle, reducing this rectangle
  19853. by the specified amount and returning the section that was removed.
  19854. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  19855. return (100, 100, 300, 50) and leave this rectangle as (100, 150, 300, 250).
  19856. If amountToRemove is greater than the height of this rectangle, it'll be clipped to
  19857. that value.
  19858. */
  19859. Rectangle removeFromTop (const ValueType amountToRemove) noexcept
  19860. {
  19861. const Rectangle r (x, y, w, jmin (amountToRemove, h));
  19862. y += r.h; h -= r.h;
  19863. return r;
  19864. }
  19865. /** Removes a strip from the left-hand edge of this rectangle, reducing this rectangle
  19866. by the specified amount and returning the section that was removed.
  19867. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  19868. return (100, 100, 50, 300) and leave this rectangle as (150, 100, 250, 300).
  19869. If amountToRemove is greater than the width of this rectangle, it'll be clipped to
  19870. that value.
  19871. */
  19872. Rectangle removeFromLeft (const ValueType amountToRemove) noexcept
  19873. {
  19874. const Rectangle r (x, y, jmin (amountToRemove, w), h);
  19875. x += r.w; w -= r.w;
  19876. return r;
  19877. }
  19878. /** Removes a strip from the right-hand edge of this rectangle, reducing this rectangle
  19879. by the specified amount and returning the section that was removed.
  19880. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  19881. return (250, 100, 50, 300) and leave this rectangle as (100, 100, 250, 300).
  19882. If amountToRemove is greater than the width of this rectangle, it'll be clipped to
  19883. that value.
  19884. */
  19885. Rectangle removeFromRight (ValueType amountToRemove) noexcept
  19886. {
  19887. amountToRemove = jmin (amountToRemove, w);
  19888. const Rectangle r (x + w - amountToRemove, y, amountToRemove, h);
  19889. w -= amountToRemove;
  19890. return r;
  19891. }
  19892. /** Removes a strip from the bottom of this rectangle, reducing this rectangle
  19893. by the specified amount and returning the section that was removed.
  19894. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  19895. return (100, 250, 300, 50) and leave this rectangle as (100, 100, 300, 250).
  19896. If amountToRemove is greater than the height of this rectangle, it'll be clipped to
  19897. that value.
  19898. */
  19899. Rectangle removeFromBottom (ValueType amountToRemove) noexcept
  19900. {
  19901. amountToRemove = jmin (amountToRemove, h);
  19902. const Rectangle r (x, y + h - amountToRemove, w, amountToRemove);
  19903. h -= amountToRemove;
  19904. return r;
  19905. }
  19906. /** Returns true if the two rectangles are identical. */
  19907. bool operator== (const Rectangle& other) const noexcept
  19908. {
  19909. return x == other.x && y == other.y
  19910. && w == other.w && h == other.h;
  19911. }
  19912. /** Returns true if the two rectangles are not identical. */
  19913. bool operator!= (const Rectangle& other) const noexcept
  19914. {
  19915. return x != other.x || y != other.y
  19916. || w != other.w || h != other.h;
  19917. }
  19918. /** Returns true if this co-ordinate is inside the rectangle. */
  19919. bool contains (const ValueType xCoord, const ValueType yCoord) const noexcept
  19920. {
  19921. return xCoord >= x && yCoord >= y && xCoord < x + w && yCoord < y + h;
  19922. }
  19923. /** Returns true if this co-ordinate is inside the rectangle. */
  19924. bool contains (const Point<ValueType>& point) const noexcept
  19925. {
  19926. return point.getX() >= x && point.getY() >= y && point.getX() < x + w && point.getY() < y + h;
  19927. }
  19928. /** Returns true if this other rectangle is completely inside this one. */
  19929. bool contains (const Rectangle& other) const noexcept
  19930. {
  19931. return x <= other.x && y <= other.y
  19932. && x + w >= other.x + other.w && y + h >= other.y + other.h;
  19933. }
  19934. /** Returns the nearest point to the specified point that lies within this rectangle. */
  19935. Point<ValueType> getConstrainedPoint (const Point<ValueType>& point) const noexcept
  19936. {
  19937. return Point<ValueType> (jlimit (x, x + w, point.getX()),
  19938. jlimit (y, y + h, point.getY()));
  19939. }
  19940. /** Returns true if any part of another rectangle overlaps this one. */
  19941. bool intersects (const Rectangle& other) const noexcept
  19942. {
  19943. return x + w > other.x
  19944. && y + h > other.y
  19945. && x < other.x + other.w
  19946. && y < other.y + other.h
  19947. && w > ValueType() && h > ValueType();
  19948. }
  19949. /** Returns the region that is the overlap between this and another rectangle.
  19950. If the two rectangles don't overlap, the rectangle returned will be empty.
  19951. */
  19952. Rectangle getIntersection (const Rectangle& other) const noexcept
  19953. {
  19954. const ValueType nx = jmax (x, other.x);
  19955. const ValueType ny = jmax (y, other.y);
  19956. const ValueType nw = jmin (x + w, other.x + other.w) - nx;
  19957. const ValueType nh = jmin (y + h, other.y + other.h) - ny;
  19958. if (nw >= ValueType() && nh >= ValueType())
  19959. return Rectangle (nx, ny, nw, nh);
  19960. return Rectangle();
  19961. }
  19962. /** Clips a rectangle so that it lies only within this one.
  19963. This is a non-static version of intersectRectangles().
  19964. Returns false if the two regions didn't overlap.
  19965. */
  19966. bool intersectRectangle (ValueType& otherX, ValueType& otherY, ValueType& otherW, ValueType& otherH) const noexcept
  19967. {
  19968. const int maxX = jmax (otherX, x);
  19969. otherW = jmin (otherX + otherW, x + w) - maxX;
  19970. if (otherW > ValueType())
  19971. {
  19972. const int maxY = jmax (otherY, y);
  19973. otherH = jmin (otherY + otherH, y + h) - maxY;
  19974. if (otherH > ValueType())
  19975. {
  19976. otherX = maxX; otherY = maxY;
  19977. return true;
  19978. }
  19979. }
  19980. return false;
  19981. }
  19982. /** Returns the smallest rectangle that contains both this one and the one passed-in.
  19983. If either this or the other rectangle are empty, they will not be counted as
  19984. part of the resulting region.
  19985. */
  19986. Rectangle getUnion (const Rectangle& other) const noexcept
  19987. {
  19988. if (other.isEmpty()) return *this;
  19989. if (isEmpty()) return other;
  19990. const ValueType newX = jmin (x, other.x);
  19991. const ValueType newY = jmin (y, other.y);
  19992. return Rectangle (newX, newY,
  19993. jmax (x + w, other.x + other.w) - newX,
  19994. jmax (y + h, other.y + other.h) - newY);
  19995. }
  19996. /** If this rectangle merged with another one results in a simple rectangle, this
  19997. will set this rectangle to the result, and return true.
  19998. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  19999. or if they form a complex region.
  20000. */
  20001. bool enlargeIfAdjacent (const Rectangle& other) noexcept
  20002. {
  20003. if (x == other.x && getRight() == other.getRight()
  20004. && (other.getBottom() >= y && other.y <= getBottom()))
  20005. {
  20006. const ValueType newY = jmin (y, other.y);
  20007. h = jmax (getBottom(), other.getBottom()) - newY;
  20008. y = newY;
  20009. return true;
  20010. }
  20011. else if (y == other.y && getBottom() == other.getBottom()
  20012. && (other.getRight() >= x && other.x <= getRight()))
  20013. {
  20014. const ValueType newX = jmin (x, other.x);
  20015. w = jmax (getRight(), other.getRight()) - newX;
  20016. x = newX;
  20017. return true;
  20018. }
  20019. return false;
  20020. }
  20021. /** If after removing another rectangle from this one the result is a simple rectangle,
  20022. this will set this object's bounds to be the result, and return true.
  20023. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  20024. or if removing the other one would form a complex region.
  20025. */
  20026. bool reduceIfPartlyContainedIn (const Rectangle& other) noexcept
  20027. {
  20028. int inside = 0;
  20029. const int otherR = other.getRight();
  20030. if (x >= other.x && x < otherR) inside = 1;
  20031. const int otherB = other.getBottom();
  20032. if (y >= other.y && y < otherB) inside |= 2;
  20033. const int r = x + w;
  20034. if (r >= other.x && r < otherR) inside |= 4;
  20035. const int b = y + h;
  20036. if (b >= other.y && b < otherB) inside |= 8;
  20037. switch (inside)
  20038. {
  20039. case 1 + 2 + 8: w = r - otherR; x = otherR; return true;
  20040. case 1 + 2 + 4: h = b - otherB; y = otherB; return true;
  20041. case 2 + 4 + 8: w = other.x - x; return true;
  20042. case 1 + 4 + 8: h = other.y - y; return true;
  20043. }
  20044. return false;
  20045. }
  20046. /** Returns the smallest rectangle that can contain the shape created by applying
  20047. a transform to this rectangle.
  20048. This should only be used on floating point rectangles.
  20049. */
  20050. Rectangle transformed (const AffineTransform& transform) const noexcept
  20051. {
  20052. float x1 = x, y1 = y;
  20053. float x2 = x + w, y2 = y;
  20054. float x3 = x, y3 = y + h;
  20055. float x4 = x2, y4 = y3;
  20056. transform.transformPoints (x1, y1, x2, y2);
  20057. transform.transformPoints (x3, y3, x4, y4);
  20058. const float rx = jmin (x1, x2, x3, x4);
  20059. const float ry = jmin (y1, y2, y3, y4);
  20060. return Rectangle (rx, ry,
  20061. jmax (x1, x2, x3, x4) - rx,
  20062. jmax (y1, y2, y3, y4) - ry);
  20063. }
  20064. /** Returns the smallest integer-aligned rectangle that completely contains this one.
  20065. This is only relevent for floating-point rectangles, of course.
  20066. @see toFloat()
  20067. */
  20068. const Rectangle<int> getSmallestIntegerContainer() const noexcept
  20069. {
  20070. const int x1 = (int) std::floor (static_cast<float> (x));
  20071. const int y1 = (int) std::floor (static_cast<float> (y));
  20072. const int x2 = (int) std::ceil (static_cast<float> (x + w));
  20073. const int y2 = (int) std::ceil (static_cast<float> (y + h));
  20074. return Rectangle<int> (x1, y1, x2 - x1, y2 - y1);
  20075. }
  20076. /** Returns the smallest Rectangle that can contain a set of points. */
  20077. static Rectangle findAreaContainingPoints (const Point<ValueType>* const points, const int numPoints) noexcept
  20078. {
  20079. if (numPoints == 0)
  20080. return Rectangle();
  20081. ValueType minX (points[0].getX());
  20082. ValueType maxX (minX);
  20083. ValueType minY (points[0].getY());
  20084. ValueType maxY (minY);
  20085. for (int i = 1; i < numPoints; ++i)
  20086. {
  20087. minX = jmin (minX, points[i].getX());
  20088. maxX = jmax (maxX, points[i].getX());
  20089. minY = jmin (minY, points[i].getY());
  20090. maxY = jmax (maxY, points[i].getY());
  20091. }
  20092. return Rectangle (minX, minY, maxX - minX, maxY - minY);
  20093. }
  20094. /** Casts this rectangle to a Rectangle<float>.
  20095. Obviously this is mainly useful for rectangles that use integer types.
  20096. @see getSmallestIntegerContainer
  20097. */
  20098. const Rectangle<float> toFloat() const noexcept
  20099. {
  20100. return Rectangle<float> (static_cast<float> (x), static_cast<float> (y),
  20101. static_cast<float> (w), static_cast<float> (h));
  20102. }
  20103. /** Static utility to intersect two sets of rectangular co-ordinates.
  20104. Returns false if the two regions didn't overlap.
  20105. @see intersectRectangle
  20106. */
  20107. static bool intersectRectangles (ValueType& x1, ValueType& y1, ValueType& w1, ValueType& h1,
  20108. const ValueType x2, const ValueType y2, const ValueType w2, const ValueType h2) noexcept
  20109. {
  20110. const ValueType x = jmax (x1, x2);
  20111. w1 = jmin (x1 + w1, x2 + w2) - x;
  20112. if (w1 > ValueType())
  20113. {
  20114. const ValueType y = jmax (y1, y2);
  20115. h1 = jmin (y1 + h1, y2 + h2) - y;
  20116. if (h1 > ValueType())
  20117. {
  20118. x1 = x; y1 = y;
  20119. return true;
  20120. }
  20121. }
  20122. return false;
  20123. }
  20124. /** Creates a string describing this rectangle.
  20125. The string will be of the form "x y width height", e.g. "100 100 400 200".
  20126. Coupled with the fromString() method, this is very handy for things like
  20127. storing rectangles (particularly component positions) in XML attributes.
  20128. @see fromString
  20129. */
  20130. String toString() const
  20131. {
  20132. String s;
  20133. s.preallocateBytes (32);
  20134. s << x << ' ' << y << ' ' << w << ' ' << h;
  20135. return s;
  20136. }
  20137. /** Parses a string containing a rectangle's details.
  20138. The string should contain 4 integer tokens, in the form "x y width height". They
  20139. can be comma or whitespace separated.
  20140. This method is intended to go with the toString() method, to form an easy way
  20141. of saving/loading rectangles as strings.
  20142. @see toString
  20143. */
  20144. static Rectangle fromString (const String& stringVersion)
  20145. {
  20146. StringArray toks;
  20147. toks.addTokens (stringVersion.trim(), ",; \t\r\n", String::empty);
  20148. return Rectangle (toks[0].trim().getIntValue(),
  20149. toks[1].trim().getIntValue(),
  20150. toks[2].trim().getIntValue(),
  20151. toks[3].trim().getIntValue());
  20152. }
  20153. private:
  20154. friend class RectangleList;
  20155. ValueType x, y, w, h;
  20156. };
  20157. #endif // __JUCE_RECTANGLE_JUCEHEADER__
  20158. /*** End of inlined file: juce_Rectangle.h ***/
  20159. /*** Start of inlined file: juce_PathStrokeType.h ***/
  20160. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  20161. #define __JUCE_PATHSTROKETYPE_JUCEHEADER__
  20162. /*** Start of inlined file: juce_Path.h ***/
  20163. #ifndef __JUCE_PATH_JUCEHEADER__
  20164. #define __JUCE_PATH_JUCEHEADER__
  20165. /*** Start of inlined file: juce_Line.h ***/
  20166. #ifndef __JUCE_LINE_JUCEHEADER__
  20167. #define __JUCE_LINE_JUCEHEADER__
  20168. /**
  20169. Represents a line.
  20170. This class contains a bunch of useful methods for various geometric
  20171. tasks.
  20172. The ValueType template parameter should be a primitive type - float or double
  20173. are what it's designed for. Integer types will work in a basic way, but some methods
  20174. that perform mathematical operations may not compile, or they may not produce
  20175. sensible results.
  20176. @see Point, Rectangle, Path, Graphics::drawLine
  20177. */
  20178. template <typename ValueType>
  20179. class Line
  20180. {
  20181. public:
  20182. /** Creates a line, using (0, 0) as its start and end points. */
  20183. Line() noexcept {}
  20184. /** Creates a copy of another line. */
  20185. Line (const Line& other) noexcept
  20186. : start (other.start),
  20187. end (other.end)
  20188. {
  20189. }
  20190. /** Creates a line based on the co-ordinates of its start and end points. */
  20191. Line (ValueType startX, ValueType startY, ValueType endX, ValueType endY) noexcept
  20192. : start (startX, startY),
  20193. end (endX, endY)
  20194. {
  20195. }
  20196. /** Creates a line from its start and end points. */
  20197. Line (const Point<ValueType>& startPoint,
  20198. const Point<ValueType>& endPoint) noexcept
  20199. : start (startPoint),
  20200. end (endPoint)
  20201. {
  20202. }
  20203. /** Copies a line from another one. */
  20204. Line& operator= (const Line& other) noexcept
  20205. {
  20206. start = other.start;
  20207. end = other.end;
  20208. return *this;
  20209. }
  20210. /** Destructor. */
  20211. ~Line() noexcept {}
  20212. /** Returns the x co-ordinate of the line's start point. */
  20213. inline ValueType getStartX() const noexcept { return start.getX(); }
  20214. /** Returns the y co-ordinate of the line's start point. */
  20215. inline ValueType getStartY() const noexcept { return start.getY(); }
  20216. /** Returns the x co-ordinate of the line's end point. */
  20217. inline ValueType getEndX() const noexcept { return end.getX(); }
  20218. /** Returns the y co-ordinate of the line's end point. */
  20219. inline ValueType getEndY() const noexcept { return end.getY(); }
  20220. /** Returns the line's start point. */
  20221. inline const Point<ValueType>& getStart() const noexcept { return start; }
  20222. /** Returns the line's end point. */
  20223. inline const Point<ValueType>& getEnd() const noexcept { return end; }
  20224. /** Changes this line's start point */
  20225. void setStart (ValueType newStartX, ValueType newStartY) noexcept { start.setXY (newStartX, newStartY); }
  20226. /** Changes this line's end point */
  20227. void setEnd (ValueType newEndX, ValueType newEndY) noexcept { end.setXY (newEndX, newEndY); }
  20228. /** Changes this line's start point */
  20229. void setStart (const Point<ValueType>& newStart) noexcept { start = newStart; }
  20230. /** Changes this line's end point */
  20231. void setEnd (const Point<ValueType>& newEnd) noexcept { end = newEnd; }
  20232. /** Returns a line that is the same as this one, but with the start and end reversed, */
  20233. const Line reversed() const noexcept { return Line (end, start); }
  20234. /** Applies an affine transform to the line's start and end points. */
  20235. void applyTransform (const AffineTransform& transform) noexcept
  20236. {
  20237. start.applyTransform (transform);
  20238. end.applyTransform (transform);
  20239. }
  20240. /** Returns the length of the line. */
  20241. ValueType getLength() const noexcept { return start.getDistanceFrom (end); }
  20242. /** Returns true if the line's start and end x co-ordinates are the same. */
  20243. bool isVertical() const noexcept { return start.getX() == end.getX(); }
  20244. /** Returns true if the line's start and end y co-ordinates are the same. */
  20245. bool isHorizontal() const noexcept { return start.getY() == end.getY(); }
  20246. /** Returns the line's angle.
  20247. This value is the number of radians clockwise from the 3 o'clock direction,
  20248. where the line's start point is considered to be at the centre.
  20249. */
  20250. ValueType getAngle() const noexcept { return start.getAngleToPoint (end); }
  20251. /** Compares two lines. */
  20252. bool operator== (const Line& other) const noexcept { return start == other.start && end == other.end; }
  20253. /** Compares two lines. */
  20254. bool operator!= (const Line& other) const noexcept { return start != other.start || end != other.end; }
  20255. /** Finds the intersection between two lines.
  20256. @param line the other line
  20257. @param intersection the position of the point where the lines meet (or
  20258. where they would meet if they were infinitely long)
  20259. the intersection (if the lines intersect). If the lines
  20260. are parallel, this will just be set to the position
  20261. of one of the line's endpoints.
  20262. @returns true if the line segments intersect; false if they dont. Even if they
  20263. don't intersect, the intersection co-ordinates returned will still
  20264. be valid
  20265. */
  20266. bool intersects (const Line& line, Point<ValueType>& intersection) const noexcept
  20267. {
  20268. return findIntersection (start, end, line.start, line.end, intersection);
  20269. }
  20270. /** Finds the intersection between two lines.
  20271. @param line the line to intersect with
  20272. @returns the point at which the lines intersect, even if this lies beyond the end of the lines
  20273. */
  20274. Point<ValueType> getIntersection (const Line& line) const noexcept
  20275. {
  20276. Point<ValueType> p;
  20277. findIntersection (start, end, line.start, line.end, p);
  20278. return p;
  20279. }
  20280. /** Returns the location of the point which is a given distance along this line.
  20281. @param distanceFromStart the distance to move along the line from its
  20282. start point. This value can be negative or longer
  20283. than the line itself
  20284. @see getPointAlongLineProportionally
  20285. */
  20286. Point<ValueType> getPointAlongLine (ValueType distanceFromStart) const noexcept
  20287. {
  20288. return start + (end - start) * (distanceFromStart / getLength());
  20289. }
  20290. /** Returns a point which is a certain distance along and to the side of this line.
  20291. This effectively moves a given distance along the line, then another distance
  20292. perpendicularly to this, and returns the resulting position.
  20293. @param distanceFromStart the distance to move along the line from its
  20294. start point. This value can be negative or longer
  20295. than the line itself
  20296. @param perpendicularDistance how far to move sideways from the line. If you're
  20297. looking along the line from its start towards its
  20298. end, then a positive value here will move to the
  20299. right, negative value move to the left.
  20300. */
  20301. Point<ValueType> getPointAlongLine (ValueType distanceFromStart,
  20302. ValueType perpendicularDistance) const noexcept
  20303. {
  20304. const Point<ValueType> delta (end - start);
  20305. const double length = juce_hypot ((double) delta.getX(),
  20306. (double) delta.getY());
  20307. if (length <= 0)
  20308. return start;
  20309. return Point<ValueType> (start.getX() + (ValueType) ((delta.getX() * distanceFromStart - delta.getY() * perpendicularDistance) / length),
  20310. start.getY() + (ValueType) ((delta.getY() * distanceFromStart + delta.getX() * perpendicularDistance) / length));
  20311. }
  20312. /** Returns the location of the point which is a given distance along this line
  20313. proportional to the line's length.
  20314. @param proportionOfLength the distance to move along the line from its
  20315. start point, in multiples of the line's length.
  20316. So a value of 0.0 will return the line's start point
  20317. and a value of 1.0 will return its end point. (This value
  20318. can be negative or greater than 1.0).
  20319. @see getPointAlongLine
  20320. */
  20321. Point<ValueType> getPointAlongLineProportionally (ValueType proportionOfLength) const noexcept
  20322. {
  20323. return start + (end - start) * proportionOfLength;
  20324. }
  20325. /** Returns the smallest distance between this line segment and a given point.
  20326. So if the point is close to the line, this will return the perpendicular
  20327. distance from the line; if the point is a long way beyond one of the line's
  20328. end-point's, it'll return the straight-line distance to the nearest end-point.
  20329. pointOnLine receives the position of the point that is found.
  20330. @returns the point's distance from the line
  20331. @see getPositionAlongLineOfNearestPoint
  20332. */
  20333. ValueType getDistanceFromPoint (const Point<ValueType>& targetPoint,
  20334. Point<ValueType>& pointOnLine) const noexcept
  20335. {
  20336. const Point<ValueType> delta (end - start);
  20337. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  20338. if (length > 0)
  20339. {
  20340. const double prop = ((targetPoint.getX() - start.getX()) * delta.getX()
  20341. + (targetPoint.getY() - start.getY()) * delta.getY()) / length;
  20342. if (prop >= 0 && prop <= 1.0)
  20343. {
  20344. pointOnLine = start + delta * (ValueType) prop;
  20345. return targetPoint.getDistanceFrom (pointOnLine);
  20346. }
  20347. }
  20348. const float fromStart = targetPoint.getDistanceFrom (start);
  20349. const float fromEnd = targetPoint.getDistanceFrom (end);
  20350. if (fromStart < fromEnd)
  20351. {
  20352. pointOnLine = start;
  20353. return fromStart;
  20354. }
  20355. else
  20356. {
  20357. pointOnLine = end;
  20358. return fromEnd;
  20359. }
  20360. }
  20361. /** Finds the point on this line which is nearest to a given point, and
  20362. returns its position as a proportional position along the line.
  20363. @returns a value 0 to 1.0 which is the distance along this line from the
  20364. line's start to the point which is nearest to the point passed-in. To
  20365. turn this number into a position, use getPointAlongLineProportionally().
  20366. @see getDistanceFromPoint, getPointAlongLineProportionally
  20367. */
  20368. ValueType findNearestProportionalPositionTo (const Point<ValueType>& point) const noexcept
  20369. {
  20370. const Point<ValueType> delta (end - start);
  20371. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  20372. return length <= 0 ? 0
  20373. : jlimit ((ValueType) 0, (ValueType) 1,
  20374. (ValueType) (((point.getX() - start.getX()) * delta.getX()
  20375. + (point.getY() - start.getY()) * delta.getY()) / length));
  20376. }
  20377. /** Finds the point on this line which is nearest to a given point.
  20378. @see getDistanceFromPoint, findNearestProportionalPositionTo
  20379. */
  20380. Point<ValueType> findNearestPointTo (const Point<ValueType>& point) const noexcept
  20381. {
  20382. return getPointAlongLineProportionally (findNearestProportionalPositionTo (point));
  20383. }
  20384. /** Returns true if the given point lies above this line.
  20385. The return value is true if the point's y coordinate is less than the y
  20386. coordinate of this line at the given x (assuming the line extends infinitely
  20387. in both directions).
  20388. */
  20389. bool isPointAbove (const Point<ValueType>& point) const noexcept
  20390. {
  20391. return start.getX() != end.getX()
  20392. && point.getY() < ((end.getY() - start.getY())
  20393. * (point.getX() - start.getX())) / (end.getX() - start.getX()) + start.getY();
  20394. }
  20395. /** Returns a shortened copy of this line.
  20396. This will chop off part of the start of this line by a certain amount, (leaving the
  20397. end-point the same), and return the new line.
  20398. */
  20399. Line withShortenedStart (ValueType distanceToShortenBy) const noexcept
  20400. {
  20401. return Line (getPointAlongLine (jmin (distanceToShortenBy, getLength())), end);
  20402. }
  20403. /** Returns a shortened copy of this line.
  20404. This will chop off part of the end of this line by a certain amount, (leaving the
  20405. start-point the same), and return the new line.
  20406. */
  20407. Line withShortenedEnd (ValueType distanceToShortenBy) const noexcept
  20408. {
  20409. const ValueType length = getLength();
  20410. return Line (start, getPointAlongLine (length - jmin (distanceToShortenBy, length)));
  20411. }
  20412. private:
  20413. Point<ValueType> start, end;
  20414. static bool findIntersection (const Point<ValueType>& p1, const Point<ValueType>& p2,
  20415. const Point<ValueType>& p3, const Point<ValueType>& p4,
  20416. Point<ValueType>& intersection) noexcept
  20417. {
  20418. if (p2 == p3)
  20419. {
  20420. intersection = p2;
  20421. return true;
  20422. }
  20423. const Point<ValueType> d1 (p2 - p1);
  20424. const Point<ValueType> d2 (p4 - p3);
  20425. const ValueType divisor = d1.getX() * d2.getY() - d2.getX() * d1.getY();
  20426. if (divisor == 0)
  20427. {
  20428. if (! (d1.isOrigin() || d2.isOrigin()))
  20429. {
  20430. if (d1.getY() == 0 && d2.getY() != 0)
  20431. {
  20432. const ValueType along = (p1.getY() - p3.getY()) / d2.getY();
  20433. intersection = p1.withX (p3.getX() + along * d2.getX());
  20434. return along >= 0 && along <= (ValueType) 1;
  20435. }
  20436. else if (d2.getY() == 0 && d1.getY() != 0)
  20437. {
  20438. const ValueType along = (p3.getY() - p1.getY()) / d1.getY();
  20439. intersection = p3.withX (p1.getX() + along * d1.getX());
  20440. return along >= 0 && along <= (ValueType) 1;
  20441. }
  20442. else if (d1.getX() == 0 && d2.getX() != 0)
  20443. {
  20444. const ValueType along = (p1.getX() - p3.getX()) / d2.getX();
  20445. intersection = p1.withY (p3.getY() + along * d2.getY());
  20446. return along >= 0 && along <= (ValueType) 1;
  20447. }
  20448. else if (d2.getX() == 0 && d1.getX() != 0)
  20449. {
  20450. const ValueType along = (p3.getX() - p1.getX()) / d1.getX();
  20451. intersection = p3.withY (p1.getY() + along * d1.getY());
  20452. return along >= 0 && along <= (ValueType) 1;
  20453. }
  20454. }
  20455. intersection = (p2 + p3) / (ValueType) 2;
  20456. return false;
  20457. }
  20458. const ValueType along1 = ((p1.getY() - p3.getY()) * d2.getX() - (p1.getX() - p3.getX()) * d2.getY()) / divisor;
  20459. intersection = p1 + d1 * along1;
  20460. if (along1 < 0 || along1 > (ValueType) 1)
  20461. return false;
  20462. const ValueType along2 = ((p1.getY() - p3.getY()) * d1.getX() - (p1.getX() - p3.getX()) * d1.getY()) / divisor;
  20463. return along2 >= 0 && along2 <= (ValueType) 1;
  20464. }
  20465. };
  20466. #endif // __JUCE_LINE_JUCEHEADER__
  20467. /*** End of inlined file: juce_Line.h ***/
  20468. /*** Start of inlined file: juce_Justification.h ***/
  20469. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  20470. #define __JUCE_JUSTIFICATION_JUCEHEADER__
  20471. /**
  20472. Represents a type of justification to be used when positioning graphical items.
  20473. e.g. it indicates whether something should be placed top-left, top-right,
  20474. centred, etc.
  20475. It is used in various places wherever this kind of information is needed.
  20476. */
  20477. class JUCE_API Justification
  20478. {
  20479. public:
  20480. /** Creates a Justification object using a combination of flags. */
  20481. inline Justification (int flags_) noexcept : flags (flags_) {}
  20482. /** Creates a copy of another Justification object. */
  20483. Justification (const Justification& other) noexcept;
  20484. /** Copies another Justification object. */
  20485. Justification& operator= (const Justification& other) noexcept;
  20486. bool operator== (const Justification& other) const noexcept { return flags == other.flags; }
  20487. bool operator!= (const Justification& other) const noexcept { return flags != other.flags; }
  20488. /** Returns the raw flags that are set for this Justification object. */
  20489. inline int getFlags() const noexcept { return flags; }
  20490. /** Tests a set of flags for this object.
  20491. @returns true if any of the flags passed in are set on this object.
  20492. */
  20493. inline bool testFlags (int flagsToTest) const noexcept { return (flags & flagsToTest) != 0; }
  20494. /** Returns just the flags from this object that deal with vertical layout. */
  20495. int getOnlyVerticalFlags() const noexcept;
  20496. /** Returns just the flags from this object that deal with horizontal layout. */
  20497. int getOnlyHorizontalFlags() const noexcept;
  20498. /** Adjusts the position of a rectangle to fit it into a space.
  20499. The (x, y) position of the rectangle will be updated to position it inside the
  20500. given space according to the justification flags.
  20501. */
  20502. template <typename ValueType>
  20503. void applyToRectangle (ValueType& x, ValueType& y, ValueType w, ValueType h,
  20504. ValueType spaceX, ValueType spaceY, ValueType spaceW, ValueType spaceH) const noexcept
  20505. {
  20506. x = spaceX;
  20507. if ((flags & horizontallyCentred) != 0) x += (spaceW - w) / (ValueType) 2;
  20508. else if ((flags & right) != 0) x += spaceW - w;
  20509. y = spaceY;
  20510. if ((flags & verticallyCentred) != 0) y += (spaceH - h) / (ValueType) 2;
  20511. else if ((flags & bottom) != 0) y += spaceH - h;
  20512. }
  20513. /** Returns the new position of a rectangle that has been justified to fit within a given space.
  20514. */
  20515. template <typename ValueType>
  20516. const Rectangle<ValueType> appliedToRectangle (const Rectangle<ValueType>& areaToAdjust,
  20517. const Rectangle<ValueType>& targetSpace) const noexcept
  20518. {
  20519. ValueType x = areaToAdjust.getX(), y = areaToAdjust.getY();
  20520. applyToRectangle (x, y, areaToAdjust.getWidth(), areaToAdjust.getHeight(),
  20521. targetSpace.getX(), targetSpace.getY(), targetSpace.getWidth(), targetSpace.getHeight());
  20522. return areaToAdjust.withPosition (x, y);
  20523. }
  20524. /** Flag values that can be combined and used in the constructor. */
  20525. enum
  20526. {
  20527. /** Indicates that the item should be aligned against the left edge of the available space. */
  20528. left = 1,
  20529. /** Indicates that the item should be aligned against the right edge of the available space. */
  20530. right = 2,
  20531. /** Indicates that the item should be placed in the centre between the left and right
  20532. sides of the available space. */
  20533. horizontallyCentred = 4,
  20534. /** Indicates that the item should be aligned against the top edge of the available space. */
  20535. top = 8,
  20536. /** Indicates that the item should be aligned against the bottom edge of the available space. */
  20537. bottom = 16,
  20538. /** Indicates that the item should be placed in the centre between the top and bottom
  20539. sides of the available space. */
  20540. verticallyCentred = 32,
  20541. /** Indicates that lines of text should be spread out to fill the maximum width
  20542. available, so that both margins are aligned vertically.
  20543. */
  20544. horizontallyJustified = 64,
  20545. /** Indicates that the item should be centred vertically and horizontally.
  20546. This is equivalent to (horizontallyCentred | verticallyCentred)
  20547. */
  20548. centred = 36,
  20549. /** Indicates that the item should be centred vertically but placed on the left hand side.
  20550. This is equivalent to (left | verticallyCentred)
  20551. */
  20552. centredLeft = 33,
  20553. /** Indicates that the item should be centred vertically but placed on the right hand side.
  20554. This is equivalent to (right | verticallyCentred)
  20555. */
  20556. centredRight = 34,
  20557. /** Indicates that the item should be centred horizontally and placed at the top.
  20558. This is equivalent to (horizontallyCentred | top)
  20559. */
  20560. centredTop = 12,
  20561. /** Indicates that the item should be centred horizontally and placed at the bottom.
  20562. This is equivalent to (horizontallyCentred | bottom)
  20563. */
  20564. centredBottom = 20,
  20565. /** Indicates that the item should be placed in the top-left corner.
  20566. This is equivalent to (left | top)
  20567. */
  20568. topLeft = 9,
  20569. /** Indicates that the item should be placed in the top-right corner.
  20570. This is equivalent to (right | top)
  20571. */
  20572. topRight = 10,
  20573. /** Indicates that the item should be placed in the bottom-left corner.
  20574. This is equivalent to (left | bottom)
  20575. */
  20576. bottomLeft = 17,
  20577. /** Indicates that the item should be placed in the bottom-left corner.
  20578. This is equivalent to (right | bottom)
  20579. */
  20580. bottomRight = 18
  20581. };
  20582. private:
  20583. int flags;
  20584. };
  20585. #endif // __JUCE_JUSTIFICATION_JUCEHEADER__
  20586. /*** End of inlined file: juce_Justification.h ***/
  20587. class Image;
  20588. class InputStream;
  20589. class OutputStream;
  20590. /**
  20591. A path is a sequence of lines and curves that may either form a closed shape
  20592. or be open-ended.
  20593. To use a path, you can create an empty one, then add lines and curves to it
  20594. to create shapes, then it can be rendered by a Graphics context or used
  20595. for geometric operations.
  20596. e.g. @code
  20597. Path myPath;
  20598. myPath.startNewSubPath (10.0f, 10.0f); // move the current position to (10, 10)
  20599. myPath.lineTo (100.0f, 200.0f); // draw a line from here to (100, 200)
  20600. myPath.quadraticTo (0.0f, 150.0f, 5.0f, 50.0f); // draw a curve that ends at (5, 50)
  20601. myPath.closeSubPath(); // close the subpath with a line back to (10, 10)
  20602. // add an ellipse as well, which will form a second sub-path within the path..
  20603. myPath.addEllipse (50.0f, 50.0f, 40.0f, 30.0f);
  20604. // double the width of the whole thing..
  20605. myPath.applyTransform (AffineTransform::scale (2.0f, 1.0f));
  20606. // and draw it to a graphics context with a 5-pixel thick outline.
  20607. g.strokePath (myPath, PathStrokeType (5.0f));
  20608. @endcode
  20609. A path object can actually contain multiple sub-paths, which may themselves
  20610. be open or closed.
  20611. @see PathFlatteningIterator, PathStrokeType, Graphics
  20612. */
  20613. class JUCE_API Path
  20614. {
  20615. public:
  20616. /** Creates an empty path. */
  20617. Path();
  20618. /** Creates a copy of another path. */
  20619. Path (const Path& other);
  20620. /** Destructor. */
  20621. ~Path();
  20622. /** Copies this path from another one. */
  20623. Path& operator= (const Path& other);
  20624. bool operator== (const Path& other) const noexcept;
  20625. bool operator!= (const Path& other) const noexcept;
  20626. /** Returns true if the path doesn't contain any lines or curves. */
  20627. bool isEmpty() const noexcept;
  20628. /** Returns the smallest rectangle that contains all points within the path.
  20629. */
  20630. Rectangle<float> getBounds() const noexcept;
  20631. /** Returns the smallest rectangle that contains all points within the path
  20632. after it's been transformed with the given tranasform matrix.
  20633. */
  20634. Rectangle<float> getBoundsTransformed (const AffineTransform& transform) const noexcept;
  20635. /** Checks whether a point lies within the path.
  20636. This is only relevent for closed paths (see closeSubPath()), and
  20637. may produce false results if used on a path which has open sub-paths.
  20638. The path's winding rule is taken into account by this method.
  20639. The tolerance parameter is the maximum error allowed when flattening the path,
  20640. so this method could return a false positive when your point is up to this distance
  20641. outside the path's boundary.
  20642. @see closeSubPath, setUsingNonZeroWinding
  20643. */
  20644. bool contains (float x, float y,
  20645. float tolerance = 1.0f) const;
  20646. /** Checks whether a point lies within the path.
  20647. This is only relevent for closed paths (see closeSubPath()), and
  20648. may produce false results if used on a path which has open sub-paths.
  20649. The path's winding rule is taken into account by this method.
  20650. The tolerance parameter is the maximum error allowed when flattening the path,
  20651. so this method could return a false positive when your point is up to this distance
  20652. outside the path's boundary.
  20653. @see closeSubPath, setUsingNonZeroWinding
  20654. */
  20655. bool contains (const Point<float>& point,
  20656. float tolerance = 1.0f) const;
  20657. /** Checks whether a line crosses the path.
  20658. This will return positive if the line crosses any of the paths constituent
  20659. lines or curves. It doesn't take into account whether the line is inside
  20660. or outside the path, or whether the path is open or closed.
  20661. The tolerance parameter is the maximum error allowed when flattening the path,
  20662. so this method could return a false positive when your point is up to this distance
  20663. outside the path's boundary.
  20664. */
  20665. bool intersectsLine (const Line<float>& line,
  20666. float tolerance = 1.0f);
  20667. /** Cuts off parts of a line to keep the parts that are either inside or
  20668. outside this path.
  20669. Note that this isn't smart enough to cope with situations where the
  20670. line would need to be cut into multiple pieces to correctly clip against
  20671. a re-entrant shape.
  20672. @param line the line to clip
  20673. @param keepSectionOutsidePath if true, it's the section outside the path
  20674. that will be kept; if false its the section inside
  20675. the path
  20676. */
  20677. Line<float> getClippedLine (const Line<float>& line, bool keepSectionOutsidePath) const;
  20678. /** Returns the length of the path.
  20679. @see getPointAlongPath
  20680. */
  20681. float getLength (const AffineTransform& transform = AffineTransform::identity) const;
  20682. /** Returns a point that is the specified distance along the path.
  20683. If the distance is greater than the total length of the path, this will return the
  20684. end point.
  20685. @see getLength
  20686. */
  20687. Point<float> getPointAlongPath (float distanceFromStart,
  20688. const AffineTransform& transform = AffineTransform::identity) const;
  20689. /** Finds the point along the path which is nearest to a given position.
  20690. This sets pointOnPath to the nearest point, and returns the distance of this point from the start
  20691. of the path.
  20692. */
  20693. float getNearestPoint (const Point<float>& targetPoint,
  20694. Point<float>& pointOnPath,
  20695. const AffineTransform& transform = AffineTransform::identity) const;
  20696. /** Removes all lines and curves, resetting the path completely. */
  20697. void clear() noexcept;
  20698. /** Begins a new subpath with a given starting position.
  20699. This will move the path's current position to the co-ordinates passed in and
  20700. make it ready to draw lines or curves starting from this position.
  20701. After adding whatever lines and curves are needed, you can either
  20702. close the current sub-path using closeSubPath() or call startNewSubPath()
  20703. to move to a new sub-path, leaving the old one open-ended.
  20704. @see lineTo, quadraticTo, cubicTo, closeSubPath
  20705. */
  20706. void startNewSubPath (float startX, float startY);
  20707. /** Begins a new subpath with a given starting position.
  20708. This will move the path's current position to the co-ordinates passed in and
  20709. make it ready to draw lines or curves starting from this position.
  20710. After adding whatever lines and curves are needed, you can either
  20711. close the current sub-path using closeSubPath() or call startNewSubPath()
  20712. to move to a new sub-path, leaving the old one open-ended.
  20713. @see lineTo, quadraticTo, cubicTo, closeSubPath
  20714. */
  20715. void startNewSubPath (const Point<float>& start);
  20716. /** Closes a the current sub-path with a line back to its start-point.
  20717. When creating a closed shape such as a triangle, don't use 3 lineTo()
  20718. calls - instead use two lineTo() calls, followed by a closeSubPath()
  20719. to join the final point back to the start.
  20720. This ensures that closes shapes are recognised as such, and this is
  20721. important for tasks like drawing strokes, which needs to know whether to
  20722. draw end-caps or not.
  20723. @see startNewSubPath, lineTo, quadraticTo, cubicTo, closeSubPath
  20724. */
  20725. void closeSubPath();
  20726. /** Adds a line from the shape's last position to a new end-point.
  20727. This will connect the end-point of the last line or curve that was added
  20728. to a new point, using a straight line.
  20729. See the class description for an example of how to add lines and curves to a path.
  20730. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  20731. */
  20732. void lineTo (float endX, float endY);
  20733. /** Adds a line from the shape's last position to a new end-point.
  20734. This will connect the end-point of the last line or curve that was added
  20735. to a new point, using a straight line.
  20736. See the class description for an example of how to add lines and curves to a path.
  20737. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  20738. */
  20739. void lineTo (const Point<float>& end);
  20740. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  20741. This will connect the end-point of the last line or curve that was added
  20742. to a new point, using a quadratic spline with one control-point.
  20743. See the class description for an example of how to add lines and curves to a path.
  20744. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  20745. */
  20746. void quadraticTo (float controlPointX,
  20747. float controlPointY,
  20748. float endPointX,
  20749. float endPointY);
  20750. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  20751. This will connect the end-point of the last line or curve that was added
  20752. to a new point, using a quadratic spline with one control-point.
  20753. See the class description for an example of how to add lines and curves to a path.
  20754. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  20755. */
  20756. void quadraticTo (const Point<float>& controlPoint,
  20757. const Point<float>& endPoint);
  20758. /** Adds a cubic bezier curve from the shape's last position to a new position.
  20759. This will connect the end-point of the last line or curve that was added
  20760. to a new point, using a cubic spline with two control-points.
  20761. See the class description for an example of how to add lines and curves to a path.
  20762. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  20763. */
  20764. void cubicTo (float controlPoint1X,
  20765. float controlPoint1Y,
  20766. float controlPoint2X,
  20767. float controlPoint2Y,
  20768. float endPointX,
  20769. float endPointY);
  20770. /** Adds a cubic bezier curve from the shape's last position to a new position.
  20771. This will connect the end-point of the last line or curve that was added
  20772. to a new point, using a cubic spline with two control-points.
  20773. See the class description for an example of how to add lines and curves to a path.
  20774. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  20775. */
  20776. void cubicTo (const Point<float>& controlPoint1,
  20777. const Point<float>& controlPoint2,
  20778. const Point<float>& endPoint);
  20779. /** Returns the last point that was added to the path by one of the drawing methods.
  20780. */
  20781. Point<float> getCurrentPosition() const;
  20782. /** Adds a rectangle to the path.
  20783. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20784. @see addRoundedRectangle, addTriangle
  20785. */
  20786. void addRectangle (float x, float y, float width, float height);
  20787. /** Adds a rectangle to the path.
  20788. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20789. @see addRoundedRectangle, addTriangle
  20790. */
  20791. template <typename ValueType>
  20792. void addRectangle (const Rectangle<ValueType>& rectangle)
  20793. {
  20794. addRectangle (static_cast <float> (rectangle.getX()), static_cast <float> (rectangle.getY()),
  20795. static_cast <float> (rectangle.getWidth()), static_cast <float> (rectangle.getHeight()));
  20796. }
  20797. /** Adds a rectangle with rounded corners to the path.
  20798. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20799. @see addRectangle, addTriangle
  20800. */
  20801. void addRoundedRectangle (float x, float y, float width, float height,
  20802. float cornerSize);
  20803. /** Adds a rectangle with rounded corners to the path.
  20804. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20805. @see addRectangle, addTriangle
  20806. */
  20807. void addRoundedRectangle (float x, float y, float width, float height,
  20808. float cornerSizeX,
  20809. float cornerSizeY);
  20810. /** Adds a rectangle with rounded corners to the path.
  20811. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20812. @see addRectangle, addTriangle
  20813. */
  20814. template <typename ValueType>
  20815. void addRoundedRectangle (const Rectangle<ValueType>& rectangle, float cornerSizeX, float cornerSizeY)
  20816. {
  20817. addRoundedRectangle (static_cast <float> (rectangle.getX()), static_cast <float> (rectangle.getY()),
  20818. static_cast <float> (rectangle.getWidth()), static_cast <float> (rectangle.getHeight()),
  20819. cornerSizeX, cornerSizeY);
  20820. }
  20821. /** Adds a rectangle with rounded corners to the path.
  20822. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20823. @see addRectangle, addTriangle
  20824. */
  20825. template <typename ValueType>
  20826. void addRoundedRectangle (const Rectangle<ValueType>& rectangle, float cornerSize)
  20827. {
  20828. addRoundedRectangle (rectangle, cornerSize, cornerSize);
  20829. }
  20830. /** Adds a triangle to the path.
  20831. The triangle is added as a new closed sub-path. (Any currently open paths will be left open).
  20832. Note that whether the vertices are specified in clockwise or anticlockwise
  20833. order will affect how the triangle is filled when it overlaps other
  20834. shapes (the winding order setting will affect this of course).
  20835. */
  20836. void addTriangle (float x1, float y1,
  20837. float x2, float y2,
  20838. float x3, float y3);
  20839. /** Adds a quadrilateral to the path.
  20840. The quad is added as a new closed sub-path. (Any currently open paths will be left open).
  20841. Note that whether the vertices are specified in clockwise or anticlockwise
  20842. order will affect how the quad is filled when it overlaps other
  20843. shapes (the winding order setting will affect this of course).
  20844. */
  20845. void addQuadrilateral (float x1, float y1,
  20846. float x2, float y2,
  20847. float x3, float y3,
  20848. float x4, float y4);
  20849. /** Adds an ellipse to the path.
  20850. The shape is added as a new sub-path. (Any currently open paths will be left open).
  20851. @see addArc
  20852. */
  20853. void addEllipse (float x, float y, float width, float height);
  20854. /** Adds an elliptical arc to the current path.
  20855. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  20856. or anti-clockwise according to whether the end angle is greater than the start. This means
  20857. that sometimes you may need to use values greater than 2*Pi for the end angle.
  20858. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  20859. @param y the top edge of the rectangle in which the elliptical outline fits
  20860. @param width the width of the rectangle in which the elliptical outline fits
  20861. @param height the height of the rectangle in which the elliptical outline fits
  20862. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  20863. top-centre of the ellipse)
  20864. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  20865. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  20866. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  20867. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  20868. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  20869. it will be added to the current sub-path, continuing from the current postition
  20870. @see addCentredArc, arcTo, addPieSegment, addEllipse
  20871. */
  20872. void addArc (float x, float y, float width, float height,
  20873. float fromRadians,
  20874. float toRadians,
  20875. bool startAsNewSubPath = false);
  20876. /** Adds an arc which is centred at a given point, and can have a rotation specified.
  20877. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  20878. or anti-clockwise according to whether the end angle is greater than the start. This means
  20879. that sometimes you may need to use values greater than 2*Pi for the end angle.
  20880. @param centreX the centre x of the ellipse
  20881. @param centreY the centre y of the ellipse
  20882. @param radiusX the horizontal radius of the ellipse
  20883. @param radiusY the vertical radius of the ellipse
  20884. @param rotationOfEllipse an angle by which the whole ellipse should be rotated about its centre, in radians (clockwise)
  20885. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  20886. top-centre of the ellipse)
  20887. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  20888. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  20889. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  20890. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  20891. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  20892. it will be added to the current sub-path, continuing from the current postition
  20893. @see addArc, arcTo
  20894. */
  20895. void addCentredArc (float centreX, float centreY,
  20896. float radiusX, float radiusY,
  20897. float rotationOfEllipse,
  20898. float fromRadians,
  20899. float toRadians,
  20900. bool startAsNewSubPath = false);
  20901. /** Adds a "pie-chart" shape to the path.
  20902. The shape is added as a new sub-path. (Any currently open paths will be
  20903. left open).
  20904. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  20905. or anti-clockwise according to whether the end angle is greater than the start. This means
  20906. that sometimes you may need to use values greater than 2*Pi for the end angle.
  20907. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  20908. @param y the top edge of the rectangle in which the elliptical outline fits
  20909. @param width the width of the rectangle in which the elliptical outline fits
  20910. @param height the height of the rectangle in which the elliptical outline fits
  20911. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  20912. top-centre of the ellipse)
  20913. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  20914. top-centre of the ellipse)
  20915. @param innerCircleProportionalSize if this is > 0, then the pie will be drawn as a curved band around a hollow
  20916. ellipse at its centre, where this value indicates the inner ellipse's size with
  20917. respect to the outer one.
  20918. @see addArc
  20919. */
  20920. void addPieSegment (float x, float y,
  20921. float width, float height,
  20922. float fromRadians,
  20923. float toRadians,
  20924. float innerCircleProportionalSize);
  20925. /** Adds a line with a specified thickness.
  20926. The line is added as a new closed sub-path. (Any currently open paths will be
  20927. left open).
  20928. @see addArrow
  20929. */
  20930. void addLineSegment (const Line<float>& line, float lineThickness);
  20931. /** Adds a line with an arrowhead on the end.
  20932. The arrow is added as a new closed sub-path. (Any currently open paths will be left open).
  20933. @see PathStrokeType::createStrokeWithArrowheads
  20934. */
  20935. void addArrow (const Line<float>& line,
  20936. float lineThickness,
  20937. float arrowheadWidth,
  20938. float arrowheadLength);
  20939. /** Adds a polygon shape to the path.
  20940. @see addStar
  20941. */
  20942. void addPolygon (const Point<float>& centre,
  20943. int numberOfSides,
  20944. float radius,
  20945. float startAngle = 0.0f);
  20946. /** Adds a star shape to the path.
  20947. @see addPolygon
  20948. */
  20949. void addStar (const Point<float>& centre,
  20950. int numberOfPoints,
  20951. float innerRadius,
  20952. float outerRadius,
  20953. float startAngle = 0.0f);
  20954. /** Adds a speech-bubble shape to the path.
  20955. @param bodyX the left of the main body area of the bubble
  20956. @param bodyY the top of the main body area of the bubble
  20957. @param bodyW the width of the main body area of the bubble
  20958. @param bodyH the height of the main body area of the bubble
  20959. @param cornerSize the amount by which to round off the corners of the main body rectangle
  20960. @param arrowTipX the x position that the tip of the arrow should connect to
  20961. @param arrowTipY the y position that the tip of the arrow should connect to
  20962. @param whichSide the side to connect the arrow to: 0 = top, 1 = left, 2 = bottom, 3 = right
  20963. @param arrowPositionAlongEdgeProportional how far along the edge of the main rectangle the
  20964. arrow's base should be - this is a proportional distance between 0 and 1.0
  20965. @param arrowWidth how wide the base of the arrow should be where it joins the main rectangle
  20966. */
  20967. void addBubble (float bodyX, float bodyY,
  20968. float bodyW, float bodyH,
  20969. float cornerSize,
  20970. float arrowTipX,
  20971. float arrowTipY,
  20972. int whichSide,
  20973. float arrowPositionAlongEdgeProportional,
  20974. float arrowWidth);
  20975. /** Adds another path to this one.
  20976. The new path is added as a new sub-path. (Any currently open paths in this
  20977. path will be left open).
  20978. @param pathToAppend the path to add
  20979. */
  20980. void addPath (const Path& pathToAppend);
  20981. /** Adds another path to this one, transforming it on the way in.
  20982. The new path is added as a new sub-path, its points being transformed by the given
  20983. matrix before being added.
  20984. @param pathToAppend the path to add
  20985. @param transformToApply an optional transform to apply to the incoming vertices
  20986. */
  20987. void addPath (const Path& pathToAppend,
  20988. const AffineTransform& transformToApply);
  20989. /** Swaps the contents of this path with another one.
  20990. The internal data of the two paths is swapped over, so this is much faster than
  20991. copying it to a temp variable and back.
  20992. */
  20993. void swapWithPath (Path& other) noexcept;
  20994. /** Applies a 2D transform to all the vertices in the path.
  20995. @see AffineTransform, scaleToFit, getTransformToScaleToFit
  20996. */
  20997. void applyTransform (const AffineTransform& transform) noexcept;
  20998. /** Rescales this path to make it fit neatly into a given space.
  20999. This is effectively a quick way of calling
  21000. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions))
  21001. @param x the x position of the rectangle to fit the path inside
  21002. @param y the y position of the rectangle to fit the path inside
  21003. @param width the width of the rectangle to fit the path inside
  21004. @param height the height of the rectangle to fit the path inside
  21005. @param preserveProportions if true, it will fit the path into the space without altering its
  21006. horizontal/vertical scale ratio; if false, it will distort the
  21007. path to fill the specified ratio both horizontally and vertically
  21008. @see applyTransform, getTransformToScaleToFit
  21009. */
  21010. void scaleToFit (float x, float y, float width, float height,
  21011. bool preserveProportions) noexcept;
  21012. /** Returns a transform that can be used to rescale the path to fit into a given space.
  21013. @param x the x position of the rectangle to fit the path inside
  21014. @param y the y position of the rectangle to fit the path inside
  21015. @param width the width of the rectangle to fit the path inside
  21016. @param height the height of the rectangle to fit the path inside
  21017. @param preserveProportions if true, it will fit the path into the space without altering its
  21018. horizontal/vertical scale ratio; if false, it will distort the
  21019. path to fill the specified ratio both horizontally and vertically
  21020. @param justificationType if the proportions are preseved, the resultant path may be smaller
  21021. than the available rectangle, so this describes how it should be
  21022. positioned within the space.
  21023. @returns an appropriate transformation
  21024. @see applyTransform, scaleToFit
  21025. */
  21026. AffineTransform getTransformToScaleToFit (float x, float y, float width, float height,
  21027. bool preserveProportions,
  21028. const Justification& justificationType = Justification::centred) const;
  21029. /** Creates a version of this path where all sharp corners have been replaced by curves.
  21030. Wherever two lines meet at an angle, this will replace the corner with a curve
  21031. of the given radius.
  21032. */
  21033. Path createPathWithRoundedCorners (float cornerRadius) const;
  21034. /** Changes the winding-rule to be used when filling the path.
  21035. If set to true (which is the default), then the path uses a non-zero-winding rule
  21036. to determine which points are inside the path. If set to false, it uses an
  21037. alternate-winding rule.
  21038. The winding-rule comes into play when areas of the shape overlap other
  21039. areas, and determines whether the overlapping regions are considered to be
  21040. inside or outside.
  21041. Changing this value just sets a flag - it doesn't affect the contents of the
  21042. path.
  21043. @see isUsingNonZeroWinding
  21044. */
  21045. void setUsingNonZeroWinding (bool isNonZeroWinding) noexcept;
  21046. /** Returns the flag that indicates whether the path should use a non-zero winding rule.
  21047. The default for a new path is true.
  21048. @see setUsingNonZeroWinding
  21049. */
  21050. bool isUsingNonZeroWinding() const { return useNonZeroWinding; }
  21051. /** Iterates the lines and curves that a path contains.
  21052. @see Path, PathFlatteningIterator
  21053. */
  21054. class JUCE_API Iterator
  21055. {
  21056. public:
  21057. Iterator (const Path& path);
  21058. ~Iterator();
  21059. /** Moves onto the next element in the path.
  21060. If this returns false, there are no more elements. If it returns true,
  21061. the elementType variable will be set to the type of the current element,
  21062. and some of the x and y variables will be filled in with values.
  21063. */
  21064. bool next();
  21065. enum PathElementType
  21066. {
  21067. startNewSubPath, /**< For this type, x1 and y1 will be set to indicate the first point in the subpath. */
  21068. lineTo, /**< For this type, x1 and y1 indicate the end point of the line. */
  21069. quadraticTo, /**< For this type, x1, y1, x2, y2 indicate the control point and endpoint of a quadratic curve. */
  21070. cubicTo, /**< For this type, x1, y1, x2, y2, x3, y3 indicate the two control points and the endpoint of a cubic curve. */
  21071. closePath /**< Indicates that the sub-path is being closed. None of the x or y values are valid in this case. */
  21072. };
  21073. PathElementType elementType;
  21074. float x1, y1, x2, y2, x3, y3;
  21075. private:
  21076. const Path& path;
  21077. size_t index;
  21078. JUCE_DECLARE_NON_COPYABLE (Iterator);
  21079. };
  21080. /** Loads a stored path from a data stream.
  21081. The data in the stream must have been written using writePathToStream().
  21082. Note that this will append the stored path to whatever is currently in
  21083. this path, so you might need to call clear() beforehand.
  21084. @see loadPathFromData, writePathToStream
  21085. */
  21086. void loadPathFromStream (InputStream& source);
  21087. /** Loads a stored path from a block of data.
  21088. This is similar to loadPathFromStream(), but just reads from a block
  21089. of data. Useful if you're including stored shapes in your code as a
  21090. block of static data.
  21091. @see loadPathFromStream, writePathToStream
  21092. */
  21093. void loadPathFromData (const void* data, int numberOfBytes);
  21094. /** Stores the path by writing it out to a stream.
  21095. After writing out a path, you can reload it using loadPathFromStream().
  21096. @see loadPathFromStream, loadPathFromData
  21097. */
  21098. void writePathToStream (OutputStream& destination) const;
  21099. /** Creates a string containing a textual representation of this path.
  21100. @see restoreFromString
  21101. */
  21102. String toString() const;
  21103. /** Restores this path from a string that was created with the toString() method.
  21104. @see toString()
  21105. */
  21106. void restoreFromString (const String& stringVersion);
  21107. private:
  21108. friend class PathFlatteningIterator;
  21109. friend class Path::Iterator;
  21110. ArrayAllocationBase <float, DummyCriticalSection> data;
  21111. size_t numElements;
  21112. float pathXMin, pathXMax, pathYMin, pathYMax;
  21113. bool useNonZeroWinding;
  21114. static const float lineMarker;
  21115. static const float moveMarker;
  21116. static const float quadMarker;
  21117. static const float cubicMarker;
  21118. static const float closeSubPathMarker;
  21119. JUCE_LEAK_DETECTOR (Path);
  21120. };
  21121. #endif // __JUCE_PATH_JUCEHEADER__
  21122. /*** End of inlined file: juce_Path.h ***/
  21123. /**
  21124. Describes a type of stroke used to render a solid outline along a path.
  21125. A PathStrokeType object can be used directly to create the shape of an outline
  21126. around a path, and is used by Graphics::strokePath to specify the type of
  21127. stroke to draw.
  21128. @see Path, Graphics::strokePath
  21129. */
  21130. class JUCE_API PathStrokeType
  21131. {
  21132. public:
  21133. /** The type of shape to use for the corners between two adjacent line segments. */
  21134. enum JointStyle
  21135. {
  21136. mitered, /**< Indicates that corners should be drawn with sharp joints.
  21137. Note that for angles that curve back on themselves, drawing a
  21138. mitre could require extending the point too far away from the
  21139. path, so a mitre limit is imposed and any corners that exceed it
  21140. are drawn as bevelled instead. */
  21141. curved, /**< Indicates that corners should be drawn as rounded-off. */
  21142. beveled /**< Indicates that corners should be drawn with a line flattening their
  21143. outside edge. */
  21144. };
  21145. /** The type shape to use for the ends of lines. */
  21146. enum EndCapStyle
  21147. {
  21148. butt, /**< Ends of lines are flat and don't extend beyond the end point. */
  21149. square, /**< Ends of lines are flat, but stick out beyond the end point for half
  21150. the thickness of the stroke. */
  21151. rounded /**< Ends of lines are rounded-off with a circular shape. */
  21152. };
  21153. /** Creates a stroke type.
  21154. @param strokeThickness the width of the line to use
  21155. @param jointStyle the type of joints to use for corners
  21156. @param endStyle the type of end-caps to use for the ends of open paths.
  21157. */
  21158. PathStrokeType (float strokeThickness,
  21159. JointStyle jointStyle = mitered,
  21160. EndCapStyle endStyle = butt) noexcept;
  21161. /** Createes a copy of another stroke type. */
  21162. PathStrokeType (const PathStrokeType& other) noexcept;
  21163. /** Copies another stroke onto this one. */
  21164. PathStrokeType& operator= (const PathStrokeType& other) noexcept;
  21165. /** Destructor. */
  21166. ~PathStrokeType() noexcept;
  21167. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  21168. @param destPath the resultant stroked outline shape will be copied into this path.
  21169. Note that it's ok for the source and destination Paths to be
  21170. the same object, so you can easily turn a path into a stroked version
  21171. of itself.
  21172. @param sourcePath the path to use as the source
  21173. @param transform an optional transform to apply to the points from the source path
  21174. as they are being used
  21175. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  21176. a higher resolution, which improves the quality if you'll later want
  21177. to enlarge the stroked path. So for example, if you're planning on drawing
  21178. the stroke at 3x the size that you're creating it, you should set this to 3.
  21179. @see createDashedStroke
  21180. */
  21181. void createStrokedPath (Path& destPath,
  21182. const Path& sourcePath,
  21183. const AffineTransform& transform = AffineTransform::identity,
  21184. float extraAccuracy = 1.0f) const;
  21185. /** Applies this stroke type to a path, creating a dashed line.
  21186. This is similar to createStrokedPath, but uses the array passed in to
  21187. break the stroke up into a series of dashes.
  21188. @param destPath the resultant stroked outline shape will be copied into this path.
  21189. Note that it's ok for the source and destination Paths to be
  21190. the same object, so you can easily turn a path into a stroked version
  21191. of itself.
  21192. @param sourcePath the path to use as the source
  21193. @param dashLengths An array of alternating on/off lengths. E.g. { 2, 3, 4, 5 } will create
  21194. a line of length 2, then skip a length of 3, then add a line of length 4,
  21195. skip 5, and keep repeating this pattern.
  21196. @param numDashLengths The number of lengths in the dashLengths array. This should really be
  21197. an even number, otherwise the pattern will get out of step as it
  21198. repeats.
  21199. @param transform an optional transform to apply to the points from the source path
  21200. as they are being used
  21201. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  21202. a higher resolution, which improves the quality if you'll later want
  21203. to enlarge the stroked path. So for example, if you're planning on drawing
  21204. the stroke at 3x the size that you're creating it, you should set this to 3.
  21205. */
  21206. void createDashedStroke (Path& destPath,
  21207. const Path& sourcePath,
  21208. const float* dashLengths,
  21209. int numDashLengths,
  21210. const AffineTransform& transform = AffineTransform::identity,
  21211. float extraAccuracy = 1.0f) const;
  21212. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  21213. @param destPath the resultant stroked outline shape will be copied into this path.
  21214. Note that it's ok for the source and destination Paths to be
  21215. the same object, so you can easily turn a path into a stroked version
  21216. of itself.
  21217. @param sourcePath the path to use as the source
  21218. @param arrowheadStartWidth the width of the arrowhead at the start of the path
  21219. @param arrowheadStartLength the length of the arrowhead at the start of the path
  21220. @param arrowheadEndWidth the width of the arrowhead at the end of the path
  21221. @param arrowheadEndLength the length of the arrowhead at the end of the path
  21222. @param transform an optional transform to apply to the points from the source path
  21223. as they are being used
  21224. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  21225. a higher resolution, which improves the quality if you'll later want
  21226. to enlarge the stroked path. So for example, if you're planning on drawing
  21227. the stroke at 3x the size that you're creating it, you should set this to 3.
  21228. @see createDashedStroke
  21229. */
  21230. void createStrokeWithArrowheads (Path& destPath,
  21231. const Path& sourcePath,
  21232. float arrowheadStartWidth, float arrowheadStartLength,
  21233. float arrowheadEndWidth, float arrowheadEndLength,
  21234. const AffineTransform& transform = AffineTransform::identity,
  21235. float extraAccuracy = 1.0f) const;
  21236. /** Returns the stroke thickness. */
  21237. float getStrokeThickness() const noexcept { return thickness; }
  21238. /** Sets the stroke thickness. */
  21239. void setStrokeThickness (float newThickness) noexcept { thickness = newThickness; }
  21240. /** Returns the joint style. */
  21241. JointStyle getJointStyle() const noexcept { return jointStyle; }
  21242. /** Sets the joint style. */
  21243. void setJointStyle (JointStyle newStyle) noexcept { jointStyle = newStyle; }
  21244. /** Returns the end-cap style. */
  21245. EndCapStyle getEndStyle() const noexcept { return endStyle; }
  21246. /** Sets the end-cap style. */
  21247. void setEndStyle (EndCapStyle newStyle) noexcept { endStyle = newStyle; }
  21248. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  21249. bool operator== (const PathStrokeType& other) const noexcept;
  21250. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  21251. bool operator!= (const PathStrokeType& other) const noexcept;
  21252. private:
  21253. float thickness;
  21254. JointStyle jointStyle;
  21255. EndCapStyle endStyle;
  21256. JUCE_LEAK_DETECTOR (PathStrokeType);
  21257. };
  21258. #endif // __JUCE_PATHSTROKETYPE_JUCEHEADER__
  21259. /*** End of inlined file: juce_PathStrokeType.h ***/
  21260. /*** Start of inlined file: juce_Colours.h ***/
  21261. #ifndef __JUCE_COLOURS_JUCEHEADER__
  21262. #define __JUCE_COLOURS_JUCEHEADER__
  21263. /*** Start of inlined file: juce_Colour.h ***/
  21264. #ifndef __JUCE_COLOUR_JUCEHEADER__
  21265. #define __JUCE_COLOUR_JUCEHEADER__
  21266. /*** Start of inlined file: juce_PixelFormats.h ***/
  21267. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  21268. #define __JUCE_PIXELFORMATS_JUCEHEADER__
  21269. #ifndef DOXYGEN
  21270. #if JUCE_MSVC
  21271. #pragma pack (push, 1)
  21272. #define PACKED
  21273. #elif JUCE_GCC
  21274. #define PACKED __attribute__((packed))
  21275. #else
  21276. #define PACKED
  21277. #endif
  21278. #endif
  21279. class PixelRGB;
  21280. class PixelAlpha;
  21281. /**
  21282. Represents a 32-bit ARGB pixel with premultiplied alpha, and can perform compositing
  21283. operations with it.
  21284. This is used internally by the imaging classes.
  21285. @see PixelRGB
  21286. */
  21287. class JUCE_API PixelARGB
  21288. {
  21289. public:
  21290. /** Creates a pixel without defining its colour. */
  21291. PixelARGB() noexcept {}
  21292. ~PixelARGB() noexcept {}
  21293. /** Creates a pixel from a 32-bit argb value.
  21294. */
  21295. PixelARGB (const uint32 argb_) noexcept
  21296. : argb (argb_)
  21297. {
  21298. }
  21299. forcedinline uint32 getARGB() const noexcept { return argb; }
  21300. forcedinline uint32 getUnpremultipliedARGB() const noexcept { PixelARGB p (argb); p.unpremultiply(); return p.getARGB(); }
  21301. forcedinline uint32 getRB() const noexcept { return 0x00ff00ff & argb; }
  21302. forcedinline uint32 getAG() const noexcept { return 0x00ff00ff & (argb >> 8); }
  21303. forcedinline uint8 getAlpha() const noexcept { return components.a; }
  21304. forcedinline uint8 getRed() const noexcept { return components.r; }
  21305. forcedinline uint8 getGreen() const noexcept { return components.g; }
  21306. forcedinline uint8 getBlue() const noexcept { return components.b; }
  21307. /** Blends another pixel onto this one.
  21308. This takes into account the opacity of the pixel being overlaid, and blends
  21309. it accordingly.
  21310. */
  21311. forcedinline void blend (const PixelARGB& src) noexcept
  21312. {
  21313. uint32 sargb = src.getARGB();
  21314. const uint32 alpha = 0x100 - (sargb >> 24);
  21315. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  21316. sargb += 0xff00ff00 & (getAG() * alpha);
  21317. argb = sargb;
  21318. }
  21319. /** Blends another pixel onto this one.
  21320. This takes into account the opacity of the pixel being overlaid, and blends
  21321. it accordingly.
  21322. */
  21323. forcedinline void blend (const PixelAlpha& src) noexcept;
  21324. /** Blends another pixel onto this one.
  21325. This takes into account the opacity of the pixel being overlaid, and blends
  21326. it accordingly.
  21327. */
  21328. forcedinline void blend (const PixelRGB& src) noexcept;
  21329. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  21330. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  21331. being used, so this can blend semi-transparently from a PixelRGB argument.
  21332. */
  21333. template <class Pixel>
  21334. forcedinline void blend (const Pixel& src, uint32 extraAlpha) noexcept
  21335. {
  21336. ++extraAlpha;
  21337. uint32 sargb = ((extraAlpha * src.getAG()) & 0xff00ff00)
  21338. | (((extraAlpha * src.getRB()) >> 8) & 0x00ff00ff);
  21339. const uint32 alpha = 0x100 - (sargb >> 24);
  21340. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  21341. sargb += 0xff00ff00 & (getAG() * alpha);
  21342. argb = sargb;
  21343. }
  21344. /** Blends another pixel with this one, creating a colour that is somewhere
  21345. between the two, as specified by the amount.
  21346. */
  21347. template <class Pixel>
  21348. forcedinline void tween (const Pixel& src, const uint32 amount) noexcept
  21349. {
  21350. uint32 drb = getRB();
  21351. drb += (((src.getRB() - drb) * amount) >> 8);
  21352. drb &= 0x00ff00ff;
  21353. uint32 dag = getAG();
  21354. dag += (((src.getAG() - dag) * amount) >> 8);
  21355. dag &= 0x00ff00ff;
  21356. dag <<= 8;
  21357. dag |= drb;
  21358. argb = dag;
  21359. }
  21360. /** Copies another pixel colour over this one.
  21361. This doesn't blend it - this colour is simply replaced by the other one.
  21362. */
  21363. template <class Pixel>
  21364. forcedinline void set (const Pixel& src) noexcept
  21365. {
  21366. argb = src.getARGB();
  21367. }
  21368. /** Replaces the colour's alpha value with another one. */
  21369. forcedinline void setAlpha (const uint8 newAlpha) noexcept
  21370. {
  21371. components.a = newAlpha;
  21372. }
  21373. /** Multiplies the colour's alpha value with another one. */
  21374. forcedinline void multiplyAlpha (int multiplier) noexcept
  21375. {
  21376. ++multiplier;
  21377. argb = ((multiplier * getAG()) & 0xff00ff00)
  21378. | (((multiplier * getRB()) >> 8) & 0x00ff00ff);
  21379. }
  21380. forcedinline void multiplyAlpha (const float multiplier) noexcept
  21381. {
  21382. multiplyAlpha ((int) (multiplier * 256.0f));
  21383. }
  21384. /** Sets the pixel's colour from individual components. */
  21385. void setARGB (const uint8 a, const uint8 r, const uint8 g, const uint8 b) noexcept
  21386. {
  21387. components.b = b;
  21388. components.g = g;
  21389. components.r = r;
  21390. components.a = a;
  21391. }
  21392. /** Premultiplies the pixel's RGB values by its alpha. */
  21393. forcedinline void premultiply() noexcept
  21394. {
  21395. const uint32 alpha = components.a;
  21396. if (alpha < 0xff)
  21397. {
  21398. if (alpha == 0)
  21399. {
  21400. components.b = 0;
  21401. components.g = 0;
  21402. components.r = 0;
  21403. }
  21404. else
  21405. {
  21406. components.b = (uint8) ((components.b * alpha + 0x7f) >> 8);
  21407. components.g = (uint8) ((components.g * alpha + 0x7f) >> 8);
  21408. components.r = (uint8) ((components.r * alpha + 0x7f) >> 8);
  21409. }
  21410. }
  21411. }
  21412. /** Unpremultiplies the pixel's RGB values. */
  21413. forcedinline void unpremultiply() noexcept
  21414. {
  21415. const uint32 alpha = components.a;
  21416. if (alpha < 0xff)
  21417. {
  21418. if (alpha == 0)
  21419. {
  21420. components.b = 0;
  21421. components.g = 0;
  21422. components.r = 0;
  21423. }
  21424. else
  21425. {
  21426. components.b = (uint8) jmin ((uint32) 0xff, (components.b * 0xff) / alpha);
  21427. components.g = (uint8) jmin ((uint32) 0xff, (components.g * 0xff) / alpha);
  21428. components.r = (uint8) jmin ((uint32) 0xff, (components.r * 0xff) / alpha);
  21429. }
  21430. }
  21431. }
  21432. forcedinline void desaturate() noexcept
  21433. {
  21434. if (components.a < 0xff && components.a > 0)
  21435. {
  21436. const int newUnpremultipliedLevel = (0xff * ((int) components.r + (int) components.g + (int) components.b) / (3 * components.a));
  21437. components.r = components.g = components.b
  21438. = (uint8) ((newUnpremultipliedLevel * components.a + 0x7f) >> 8);
  21439. }
  21440. else
  21441. {
  21442. components.r = components.g = components.b
  21443. = (uint8) (((int) components.r + (int) components.g + (int) components.b) / 3);
  21444. }
  21445. }
  21446. /** The indexes of the different components in the byte layout of this type of colour. */
  21447. #if JUCE_BIG_ENDIAN
  21448. enum { indexA = 0, indexR = 1, indexG = 2, indexB = 3 };
  21449. #else
  21450. enum { indexA = 3, indexR = 2, indexG = 1, indexB = 0 };
  21451. #endif
  21452. private:
  21453. union
  21454. {
  21455. uint32 argb;
  21456. struct
  21457. {
  21458. #if JUCE_BIG_ENDIAN
  21459. uint8 a : 8, r : 8, g : 8, b : 8;
  21460. #else
  21461. uint8 b, g, r, a;
  21462. #endif
  21463. } PACKED components;
  21464. };
  21465. }
  21466. #ifndef DOXYGEN
  21467. PACKED
  21468. #endif
  21469. ;
  21470. /**
  21471. Represents a 24-bit RGB pixel, and can perform compositing operations on it.
  21472. This is used internally by the imaging classes.
  21473. @see PixelARGB
  21474. */
  21475. class JUCE_API PixelRGB
  21476. {
  21477. public:
  21478. /** Creates a pixel without defining its colour. */
  21479. PixelRGB() noexcept {}
  21480. ~PixelRGB() noexcept {}
  21481. /** Creates a pixel from a 32-bit argb value.
  21482. (The argb format is that used by PixelARGB)
  21483. */
  21484. PixelRGB (const uint32 argb) noexcept
  21485. {
  21486. r = (uint8) (argb >> 16);
  21487. g = (uint8) (argb >> 8);
  21488. b = (uint8) (argb);
  21489. }
  21490. forcedinline uint32 getARGB() const noexcept { return 0xff000000 | b | (g << 8) | (r << 16); }
  21491. forcedinline uint32 getUnpremultipliedARGB() const noexcept { return getARGB(); }
  21492. forcedinline uint32 getRB() const noexcept { return b | (uint32) (r << 16); }
  21493. forcedinline uint32 getAG() const noexcept { return 0xff0000 | g; }
  21494. forcedinline uint8 getAlpha() const noexcept { return 0xff; }
  21495. forcedinline uint8 getRed() const noexcept { return r; }
  21496. forcedinline uint8 getGreen() const noexcept { return g; }
  21497. forcedinline uint8 getBlue() const noexcept { return b; }
  21498. /** Blends another pixel onto this one.
  21499. This takes into account the opacity of the pixel being overlaid, and blends
  21500. it accordingly.
  21501. */
  21502. forcedinline void blend (const PixelARGB& src) noexcept
  21503. {
  21504. uint32 sargb = src.getARGB();
  21505. const uint32 alpha = 0x100 - (sargb >> 24);
  21506. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  21507. sargb += 0x0000ff00 & (g * alpha);
  21508. r = (uint8) (sargb >> 16);
  21509. g = (uint8) (sargb >> 8);
  21510. b = (uint8) sargb;
  21511. }
  21512. forcedinline void blend (const PixelRGB& src) noexcept
  21513. {
  21514. set (src);
  21515. }
  21516. forcedinline void blend (const PixelAlpha& src) noexcept;
  21517. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  21518. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  21519. being used, so this can blend semi-transparently from a PixelRGB argument.
  21520. */
  21521. template <class Pixel>
  21522. forcedinline void blend (const Pixel& src, uint32 extraAlpha) noexcept
  21523. {
  21524. ++extraAlpha;
  21525. const uint32 srb = (extraAlpha * src.getRB()) >> 8;
  21526. const uint32 sag = extraAlpha * src.getAG();
  21527. uint32 sargb = (sag & 0xff00ff00) | (srb & 0x00ff00ff);
  21528. const uint32 alpha = 0x100 - (sargb >> 24);
  21529. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  21530. sargb += 0x0000ff00 & (g * alpha);
  21531. b = (uint8) sargb;
  21532. g = (uint8) (sargb >> 8);
  21533. r = (uint8) (sargb >> 16);
  21534. }
  21535. /** Blends another pixel with this one, creating a colour that is somewhere
  21536. between the two, as specified by the amount.
  21537. */
  21538. template <class Pixel>
  21539. forcedinline void tween (const Pixel& src, const uint32 amount) noexcept
  21540. {
  21541. uint32 drb = getRB();
  21542. drb += (((src.getRB() - drb) * amount) >> 8);
  21543. uint32 dag = getAG();
  21544. dag += (((src.getAG() - dag) * amount) >> 8);
  21545. b = (uint8) drb;
  21546. g = (uint8) dag;
  21547. r = (uint8) (drb >> 16);
  21548. }
  21549. /** Copies another pixel colour over this one.
  21550. This doesn't blend it - this colour is simply replaced by the other one.
  21551. Because PixelRGB has no alpha channel, any alpha value in the source pixel
  21552. is thrown away.
  21553. */
  21554. template <class Pixel>
  21555. forcedinline void set (const Pixel& src) noexcept
  21556. {
  21557. b = src.getBlue();
  21558. g = src.getGreen();
  21559. r = src.getRed();
  21560. }
  21561. /** This method is included for compatibility with the PixelARGB class. */
  21562. forcedinline void setAlpha (const uint8) noexcept {}
  21563. /** Multiplies the colour's alpha value with another one. */
  21564. forcedinline void multiplyAlpha (int) noexcept {}
  21565. /** Sets the pixel's colour from individual components. */
  21566. void setARGB (const uint8, const uint8 r_, const uint8 g_, const uint8 b_) noexcept
  21567. {
  21568. r = r_;
  21569. g = g_;
  21570. b = b_;
  21571. }
  21572. /** Premultiplies the pixel's RGB values by its alpha. */
  21573. forcedinline void premultiply() noexcept {}
  21574. /** Unpremultiplies the pixel's RGB values. */
  21575. forcedinline void unpremultiply() noexcept {}
  21576. forcedinline void desaturate() noexcept
  21577. {
  21578. r = g = b = (uint8) (((int) r + (int) g + (int) b) / 3);
  21579. }
  21580. /** The indexes of the different components in the byte layout of this type of colour. */
  21581. #if JUCE_MAC
  21582. enum { indexR = 0, indexG = 1, indexB = 2 };
  21583. #else
  21584. enum { indexR = 2, indexG = 1, indexB = 0 };
  21585. #endif
  21586. private:
  21587. #if JUCE_MAC
  21588. uint8 r, g, b;
  21589. #else
  21590. uint8 b, g, r;
  21591. #endif
  21592. }
  21593. #ifndef DOXYGEN
  21594. PACKED
  21595. #endif
  21596. ;
  21597. forcedinline void PixelARGB::blend (const PixelRGB& src) noexcept
  21598. {
  21599. set (src);
  21600. }
  21601. /**
  21602. Represents an 8-bit single-channel pixel, and can perform compositing operations on it.
  21603. This is used internally by the imaging classes.
  21604. @see PixelARGB, PixelRGB
  21605. */
  21606. class JUCE_API PixelAlpha
  21607. {
  21608. public:
  21609. /** Creates a pixel without defining its colour. */
  21610. PixelAlpha() noexcept {}
  21611. ~PixelAlpha() noexcept {}
  21612. /** Creates a pixel from a 32-bit argb value.
  21613. (The argb format is that used by PixelARGB)
  21614. */
  21615. PixelAlpha (const uint32 argb) noexcept
  21616. {
  21617. a = (uint8) (argb >> 24);
  21618. }
  21619. forcedinline uint32 getARGB() const noexcept { return (((uint32) a) << 24) | (((uint32) a) << 16) | (((uint32) a) << 8) | a; }
  21620. forcedinline uint32 getUnpremultipliedARGB() const noexcept { return (((uint32) a) << 24) | 0xffffff; }
  21621. forcedinline uint32 getRB() const noexcept { return (((uint32) a) << 16) | a; }
  21622. forcedinline uint32 getAG() const noexcept { return (((uint32) a) << 16) | a; }
  21623. forcedinline uint8 getAlpha() const noexcept { return a; }
  21624. forcedinline uint8 getRed() const noexcept { return 0; }
  21625. forcedinline uint8 getGreen() const noexcept { return 0; }
  21626. forcedinline uint8 getBlue() const noexcept { return 0; }
  21627. /** Blends another pixel onto this one.
  21628. This takes into account the opacity of the pixel being overlaid, and blends
  21629. it accordingly.
  21630. */
  21631. template <class Pixel>
  21632. forcedinline void blend (const Pixel& src) noexcept
  21633. {
  21634. const int srcA = src.getAlpha();
  21635. a = (uint8) ((a * (0x100 - srcA) >> 8) + srcA);
  21636. }
  21637. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  21638. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  21639. being used, so this can blend semi-transparently from a PixelRGB argument.
  21640. */
  21641. template <class Pixel>
  21642. forcedinline void blend (const Pixel& src, uint32 extraAlpha) noexcept
  21643. {
  21644. ++extraAlpha;
  21645. const int srcAlpha = (extraAlpha * src.getAlpha()) >> 8;
  21646. a = (uint8) ((a * (0x100 - srcAlpha) >> 8) + srcAlpha);
  21647. }
  21648. /** Blends another pixel with this one, creating a colour that is somewhere
  21649. between the two, as specified by the amount.
  21650. */
  21651. template <class Pixel>
  21652. forcedinline void tween (const Pixel& src, const uint32 amount) noexcept
  21653. {
  21654. a += ((src,getAlpha() - a) * amount) >> 8;
  21655. }
  21656. /** Copies another pixel colour over this one.
  21657. This doesn't blend it - this colour is simply replaced by the other one.
  21658. */
  21659. template <class Pixel>
  21660. forcedinline void set (const Pixel& src) noexcept
  21661. {
  21662. a = src.getAlpha();
  21663. }
  21664. /** Replaces the colour's alpha value with another one. */
  21665. forcedinline void setAlpha (const uint8 newAlpha) noexcept
  21666. {
  21667. a = newAlpha;
  21668. }
  21669. /** Multiplies the colour's alpha value with another one. */
  21670. forcedinline void multiplyAlpha (int multiplier) noexcept
  21671. {
  21672. ++multiplier;
  21673. a = (uint8) ((a * multiplier) >> 8);
  21674. }
  21675. forcedinline void multiplyAlpha (const float multiplier) noexcept
  21676. {
  21677. a = (uint8) (a * multiplier);
  21678. }
  21679. /** Sets the pixel's colour from individual components. */
  21680. forcedinline void setARGB (const uint8 a_, const uint8 /*r*/, const uint8 /*g*/, const uint8 /*b*/) noexcept
  21681. {
  21682. a = a_;
  21683. }
  21684. /** Premultiplies the pixel's RGB values by its alpha. */
  21685. forcedinline void premultiply() noexcept
  21686. {
  21687. }
  21688. /** Unpremultiplies the pixel's RGB values. */
  21689. forcedinline void unpremultiply() noexcept
  21690. {
  21691. }
  21692. forcedinline void desaturate() noexcept
  21693. {
  21694. }
  21695. /** The indexes of the different components in the byte layout of this type of colour. */
  21696. enum { indexA = 0 };
  21697. private:
  21698. uint8 a : 8;
  21699. }
  21700. #ifndef DOXYGEN
  21701. PACKED
  21702. #endif
  21703. ;
  21704. forcedinline void PixelRGB::blend (const PixelAlpha& src) noexcept
  21705. {
  21706. blend (PixelARGB (src.getARGB()));
  21707. }
  21708. forcedinline void PixelARGB::blend (const PixelAlpha& src) noexcept
  21709. {
  21710. uint32 sargb = src.getARGB();
  21711. const uint32 alpha = 0x100 - (sargb >> 24);
  21712. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  21713. sargb += 0xff00ff00 & (getAG() * alpha);
  21714. argb = sargb;
  21715. }
  21716. #if JUCE_MSVC
  21717. #pragma pack (pop)
  21718. #endif
  21719. #undef PACKED
  21720. #endif // __JUCE_PIXELFORMATS_JUCEHEADER__
  21721. /*** End of inlined file: juce_PixelFormats.h ***/
  21722. /**
  21723. Represents a colour, also including a transparency value.
  21724. The colour is stored internally as unsigned 8-bit red, green, blue and alpha values.
  21725. */
  21726. class JUCE_API Colour
  21727. {
  21728. public:
  21729. /** Creates a transparent black colour. */
  21730. Colour() noexcept;
  21731. /** Creates a copy of another Colour object. */
  21732. Colour (const Colour& other) noexcept;
  21733. /** Creates a colour from a 32-bit ARGB value.
  21734. The format of this number is:
  21735. ((alpha << 24) | (red << 16) | (green << 8) | blue).
  21736. All components in the range 0x00 to 0xff.
  21737. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  21738. @see getPixelARGB
  21739. */
  21740. explicit Colour (uint32 argb) noexcept;
  21741. /** Creates an opaque colour using 8-bit red, green and blue values */
  21742. Colour (uint8 red,
  21743. uint8 green,
  21744. uint8 blue) noexcept;
  21745. /** Creates an opaque colour using 8-bit red, green and blue values */
  21746. static Colour fromRGB (uint8 red,
  21747. uint8 green,
  21748. uint8 blue) noexcept;
  21749. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  21750. Colour (uint8 red,
  21751. uint8 green,
  21752. uint8 blue,
  21753. uint8 alpha) noexcept;
  21754. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  21755. static Colour fromRGBA (uint8 red,
  21756. uint8 green,
  21757. uint8 blue,
  21758. uint8 alpha) noexcept;
  21759. /** Creates a colour from 8-bit red, green, and blue values, and a floating-point alpha.
  21760. Alpha of 0.0 is transparent, alpha of 1.0f is opaque.
  21761. Values outside the valid range will be clipped.
  21762. */
  21763. Colour (uint8 red,
  21764. uint8 green,
  21765. uint8 blue,
  21766. float alpha) noexcept;
  21767. /** Creates a colour using 8-bit red, green, blue and float alpha values. */
  21768. static Colour fromRGBAFloat (uint8 red,
  21769. uint8 green,
  21770. uint8 blue,
  21771. float alpha) noexcept;
  21772. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  21773. The floating point values must be between 0.0 and 1.0.
  21774. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  21775. Values outside the valid range will be clipped.
  21776. */
  21777. Colour (float hue,
  21778. float saturation,
  21779. float brightness,
  21780. uint8 alpha) noexcept;
  21781. /** Creates a colour using floating point hue, saturation, brightness and alpha values.
  21782. All values must be between 0.0 and 1.0.
  21783. Numbers outside the valid range will be clipped.
  21784. */
  21785. Colour (float hue,
  21786. float saturation,
  21787. float brightness,
  21788. float alpha) noexcept;
  21789. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  21790. The floating point values must be between 0.0 and 1.0.
  21791. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  21792. Values outside the valid range will be clipped.
  21793. */
  21794. static Colour fromHSV (float hue,
  21795. float saturation,
  21796. float brightness,
  21797. float alpha) noexcept;
  21798. /** Destructor. */
  21799. ~Colour() noexcept;
  21800. /** Copies another Colour object. */
  21801. Colour& operator= (const Colour& other) noexcept;
  21802. /** Compares two colours. */
  21803. bool operator== (const Colour& other) const noexcept;
  21804. /** Compares two colours. */
  21805. bool operator!= (const Colour& other) const noexcept;
  21806. /** Returns the red component of this colour.
  21807. @returns a value between 0x00 and 0xff.
  21808. */
  21809. uint8 getRed() const noexcept { return argb.getRed(); }
  21810. /** Returns the green component of this colour.
  21811. @returns a value between 0x00 and 0xff.
  21812. */
  21813. uint8 getGreen() const noexcept { return argb.getGreen(); }
  21814. /** Returns the blue component of this colour.
  21815. @returns a value between 0x00 and 0xff.
  21816. */
  21817. uint8 getBlue() const noexcept { return argb.getBlue(); }
  21818. /** Returns the red component of this colour as a floating point value.
  21819. @returns a value between 0.0 and 1.0
  21820. */
  21821. float getFloatRed() const noexcept;
  21822. /** Returns the green component of this colour as a floating point value.
  21823. @returns a value between 0.0 and 1.0
  21824. */
  21825. float getFloatGreen() const noexcept;
  21826. /** Returns the blue component of this colour as a floating point value.
  21827. @returns a value between 0.0 and 1.0
  21828. */
  21829. float getFloatBlue() const noexcept;
  21830. /** Returns a premultiplied ARGB pixel object that represents this colour.
  21831. */
  21832. const PixelARGB getPixelARGB() const noexcept;
  21833. /** Returns a 32-bit integer that represents this colour.
  21834. The format of this number is:
  21835. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  21836. */
  21837. uint32 getARGB() const noexcept;
  21838. /** Returns the colour's alpha (opacity).
  21839. Alpha of 0x00 is completely transparent, 0xff is completely opaque.
  21840. */
  21841. uint8 getAlpha() const noexcept { return argb.getAlpha(); }
  21842. /** Returns the colour's alpha (opacity) as a floating point value.
  21843. Alpha of 0.0 is completely transparent, 1.0 is completely opaque.
  21844. */
  21845. float getFloatAlpha() const noexcept;
  21846. /** Returns true if this colour is completely opaque.
  21847. Equivalent to (getAlpha() == 0xff).
  21848. */
  21849. bool isOpaque() const noexcept;
  21850. /** Returns true if this colour is completely transparent.
  21851. Equivalent to (getAlpha() == 0x00).
  21852. */
  21853. bool isTransparent() const noexcept;
  21854. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  21855. Colour withAlpha (uint8 newAlpha) const noexcept;
  21856. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  21857. Colour withAlpha (float newAlpha) const noexcept;
  21858. /** Returns a colour that's the same colour as this one, but with a modified alpha value.
  21859. The new colour's alpha will be this object's alpha multiplied by the value passed-in.
  21860. */
  21861. Colour withMultipliedAlpha (float alphaMultiplier) const noexcept;
  21862. /** Returns a colour that is the result of alpha-compositing a new colour over this one.
  21863. If the foreground colour is semi-transparent, it is blended onto this colour
  21864. accordingly.
  21865. */
  21866. Colour overlaidWith (const Colour& foregroundColour) const noexcept;
  21867. /** Returns a colour that lies somewhere between this one and another.
  21868. If amountOfOther is zero, the result is 100% this colour, if amountOfOther
  21869. is 1.0, the result is 100% of the other colour.
  21870. */
  21871. Colour interpolatedWith (const Colour& other, float proportionOfOther) const noexcept;
  21872. /** Returns the colour's hue component.
  21873. The value returned is in the range 0.0 to 1.0
  21874. */
  21875. float getHue() const noexcept;
  21876. /** Returns the colour's saturation component.
  21877. The value returned is in the range 0.0 to 1.0
  21878. */
  21879. float getSaturation() const noexcept;
  21880. /** Returns the colour's brightness component.
  21881. The value returned is in the range 0.0 to 1.0
  21882. */
  21883. float getBrightness() const noexcept;
  21884. /** Returns the colour's hue, saturation and brightness components all at once.
  21885. The values returned are in the range 0.0 to 1.0
  21886. */
  21887. void getHSB (float& hue,
  21888. float& saturation,
  21889. float& brightness) const noexcept;
  21890. /** Returns a copy of this colour with a different hue. */
  21891. Colour withHue (float newHue) const noexcept;
  21892. /** Returns a copy of this colour with a different saturation. */
  21893. Colour withSaturation (float newSaturation) const noexcept;
  21894. /** Returns a copy of this colour with a different brightness.
  21895. @see brighter, darker, withMultipliedBrightness
  21896. */
  21897. Colour withBrightness (float newBrightness) const noexcept;
  21898. /** Returns a copy of this colour with it hue rotated.
  21899. The new colour's hue is ((this->getHue() + amountToRotate) % 1.0)
  21900. @see brighter, darker, withMultipliedBrightness
  21901. */
  21902. Colour withRotatedHue (float amountToRotate) const noexcept;
  21903. /** Returns a copy of this colour with its saturation multiplied by the given value.
  21904. The new colour's saturation is (this->getSaturation() * multiplier)
  21905. (the result is clipped to legal limits).
  21906. */
  21907. Colour withMultipliedSaturation (float multiplier) const noexcept;
  21908. /** Returns a copy of this colour with its brightness multiplied by the given value.
  21909. The new colour's saturation is (this->getBrightness() * multiplier)
  21910. (the result is clipped to legal limits).
  21911. */
  21912. Colour withMultipliedBrightness (float amount) const noexcept;
  21913. /** Returns a brighter version of this colour.
  21914. @param amountBrighter how much brighter to make it - a value from 0 to 1.0 where 0 is
  21915. unchanged, and higher values make it brighter
  21916. @see withMultipliedBrightness
  21917. */
  21918. Colour brighter (float amountBrighter = 0.4f) const noexcept;
  21919. /** Returns a darker version of this colour.
  21920. @param amountDarker how much darker to make it - a value from 0 to 1.0 where 0 is
  21921. unchanged, and higher values make it darker
  21922. @see withMultipliedBrightness
  21923. */
  21924. Colour darker (float amountDarker = 0.4f) const noexcept;
  21925. /** Returns a colour that will be clearly visible against this colour.
  21926. The amount parameter indicates how contrasting the new colour should
  21927. be, so e.g. Colours::black.contrasting (0.1f) will return a colour
  21928. that's just a little bit lighter; Colours::black.contrasting (1.0f) will
  21929. return white; Colours::white.contrasting (1.0f) will return black, etc.
  21930. */
  21931. Colour contrasting (float amount = 1.0f) const noexcept;
  21932. /** Returns a colour that contrasts against two colours.
  21933. Looks for a colour that contrasts with both of the colours passed-in.
  21934. Handy for things like choosing a highlight colour in text editors, etc.
  21935. */
  21936. static Colour contrasting (const Colour& colour1,
  21937. const Colour& colour2) noexcept;
  21938. /** Returns an opaque shade of grey.
  21939. @param brightness the level of grey to return - 0 is black, 1.0 is white
  21940. */
  21941. static Colour greyLevel (float brightness) noexcept;
  21942. /** Returns a stringified version of this colour.
  21943. The string can be turned back into a colour using the fromString() method.
  21944. */
  21945. String toString() const;
  21946. /** Reads the colour from a string that was created with toString().
  21947. */
  21948. static Colour fromString (const String& encodedColourString);
  21949. /** Returns the colour as a hex string in the form RRGGBB or AARRGGBB. */
  21950. String toDisplayString (bool includeAlphaValue) const;
  21951. private:
  21952. PixelARGB argb;
  21953. };
  21954. #endif // __JUCE_COLOUR_JUCEHEADER__
  21955. /*** End of inlined file: juce_Colour.h ***/
  21956. /**
  21957. Contains a set of predefined named colours (mostly standard HTML colours)
  21958. @see Colour, Colours::greyLevel
  21959. */
  21960. class Colours
  21961. {
  21962. public:
  21963. static JUCE_API const Colour
  21964. transparentBlack, /**< ARGB = 0x00000000 */
  21965. transparentWhite, /**< ARGB = 0x00ffffff */
  21966. black, /**< ARGB = 0xff000000 */
  21967. white, /**< ARGB = 0xffffffff */
  21968. blue, /**< ARGB = 0xff0000ff */
  21969. grey, /**< ARGB = 0xff808080 */
  21970. green, /**< ARGB = 0xff008000 */
  21971. red, /**< ARGB = 0xffff0000 */
  21972. yellow, /**< ARGB = 0xffffff00 */
  21973. aliceblue, antiquewhite, aqua, aquamarine,
  21974. azure, beige, bisque, blanchedalmond,
  21975. blueviolet, brown, burlywood, cadetblue,
  21976. chartreuse, chocolate, coral, cornflowerblue,
  21977. cornsilk, crimson, cyan, darkblue,
  21978. darkcyan, darkgoldenrod, darkgrey, darkgreen,
  21979. darkkhaki, darkmagenta, darkolivegreen, darkorange,
  21980. darkorchid, darkred, darksalmon, darkseagreen,
  21981. darkslateblue, darkslategrey, darkturquoise, darkviolet,
  21982. deeppink, deepskyblue, dimgrey, dodgerblue,
  21983. firebrick, floralwhite, forestgreen, fuchsia,
  21984. gainsboro, gold, goldenrod, greenyellow,
  21985. honeydew, hotpink, indianred, indigo,
  21986. ivory, khaki, lavender, lavenderblush,
  21987. lemonchiffon, lightblue, lightcoral, lightcyan,
  21988. lightgoldenrodyellow, lightgreen, lightgrey, lightpink,
  21989. lightsalmon, lightseagreen, lightskyblue, lightslategrey,
  21990. lightsteelblue, lightyellow, lime, limegreen,
  21991. linen, magenta, maroon, mediumaquamarine,
  21992. mediumblue, mediumorchid, mediumpurple, mediumseagreen,
  21993. mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred,
  21994. midnightblue, mintcream, mistyrose, navajowhite,
  21995. navy, oldlace, olive, olivedrab,
  21996. orange, orangered, orchid, palegoldenrod,
  21997. palegreen, paleturquoise, palevioletred, papayawhip,
  21998. peachpuff, peru, pink, plum,
  21999. powderblue, purple, rosybrown, royalblue,
  22000. saddlebrown, salmon, sandybrown, seagreen,
  22001. seashell, sienna, silver, skyblue,
  22002. slateblue, slategrey, snow, springgreen,
  22003. steelblue, tan, teal, thistle,
  22004. tomato, turquoise, violet, wheat,
  22005. whitesmoke, yellowgreen;
  22006. /** Attempts to look up a string in the list of known colour names, and return
  22007. the appropriate colour.
  22008. A non-case-sensitive search is made of the list of predefined colours, and
  22009. if a match is found, that colour is returned. If no match is found, the
  22010. colour passed in as the defaultColour parameter is returned.
  22011. */
  22012. static JUCE_API const Colour findColourForName (const String& colourName,
  22013. const Colour& defaultColour);
  22014. private:
  22015. // this isn't a class you should ever instantiate - it's just here for the
  22016. // static values in it.
  22017. Colours();
  22018. JUCE_DECLARE_NON_COPYABLE (Colours);
  22019. };
  22020. #endif // __JUCE_COLOURS_JUCEHEADER__
  22021. /*** End of inlined file: juce_Colours.h ***/
  22022. /*** Start of inlined file: juce_ColourGradient.h ***/
  22023. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  22024. #define __JUCE_COLOURGRADIENT_JUCEHEADER__
  22025. /**
  22026. Describes the layout and colours that should be used to paint a colour gradient.
  22027. @see Graphics::setGradientFill
  22028. */
  22029. class JUCE_API ColourGradient
  22030. {
  22031. public:
  22032. /** Creates a gradient object.
  22033. (x1, y1) is the location to draw with colour1. Likewise (x2, y2) is where
  22034. colour2 should be. In between them there's a gradient.
  22035. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  22036. its centre.
  22037. The alpha transparencies of the colours are used, so note that
  22038. if you blend from transparent to a solid colour, the RGB of the transparent
  22039. colour will become visible in parts of the gradient. e.g. blending
  22040. from Colour::transparentBlack to Colours::white will produce a
  22041. muddy grey colour midway, but Colour::transparentWhite to Colours::white
  22042. will be white all the way across.
  22043. @see ColourGradient
  22044. */
  22045. ColourGradient (const Colour& colour1, float x1, float y1,
  22046. const Colour& colour2, float x2, float y2,
  22047. bool isRadial);
  22048. /** Creates an uninitialised gradient.
  22049. If you use this constructor instead of the other one, be sure to set all the
  22050. object's public member variables before using it!
  22051. */
  22052. ColourGradient() noexcept;
  22053. /** Destructor */
  22054. ~ColourGradient();
  22055. /** Removes any colours that have been added.
  22056. This will also remove any start and end colours, so the gradient won't work. You'll
  22057. need to add more colours with addColour().
  22058. */
  22059. void clearColours();
  22060. /** Adds a colour at a point along the length of the gradient.
  22061. This allows the gradient to go through a spectrum of colours, instead of just a
  22062. start and end colour.
  22063. @param proportionAlongGradient a value between 0 and 1.0, which is the proportion
  22064. of the distance along the line between the two points
  22065. at which the colour should occur.
  22066. @param colour the colour that should be used at this point
  22067. @returns the index at which the new point was added
  22068. */
  22069. int addColour (double proportionAlongGradient,
  22070. const Colour& colour);
  22071. /** Removes one of the colours from the gradient. */
  22072. void removeColour (int index);
  22073. /** Multiplies the alpha value of all the colours by the given scale factor */
  22074. void multiplyOpacity (float multiplier) noexcept;
  22075. /** Returns the number of colour-stops that have been added. */
  22076. int getNumColours() const noexcept;
  22077. /** Returns the position along the length of the gradient of the colour with this index.
  22078. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  22079. */
  22080. double getColourPosition (int index) const noexcept;
  22081. /** Returns the colour that was added with a given index.
  22082. The index is from 0 to getNumColours() - 1.
  22083. */
  22084. const Colour getColour (int index) const noexcept;
  22085. /** Changes the colour at a given index.
  22086. The index is from 0 to getNumColours() - 1.
  22087. */
  22088. void setColour (int index, const Colour& newColour) noexcept;
  22089. /** Returns the an interpolated colour at any position along the gradient.
  22090. @param position the position along the gradient, between 0 and 1
  22091. */
  22092. Colour getColourAtPosition (double position) const noexcept;
  22093. /** Creates a set of interpolated premultiplied ARGB values.
  22094. This will resize the HeapBlock, fill it with the colours, and will return the number of
  22095. colours that it added.
  22096. */
  22097. int createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& resultLookupTable) const;
  22098. /** Returns true if all colours are opaque. */
  22099. bool isOpaque() const noexcept;
  22100. /** Returns true if all colours are completely transparent. */
  22101. bool isInvisible() const noexcept;
  22102. Point<float> point1, point2;
  22103. /** If true, the gradient should be filled circularly, centred around
  22104. point1, with point2 defining a point on the circumference.
  22105. If false, the gradient is linear between the two points.
  22106. */
  22107. bool isRadial;
  22108. bool operator== (const ColourGradient& other) const noexcept;
  22109. bool operator!= (const ColourGradient& other) const noexcept;
  22110. private:
  22111. struct ColourPoint
  22112. {
  22113. ColourPoint() noexcept {}
  22114. ColourPoint (const double position_, const Colour& colour_) noexcept
  22115. : position (position_), colour (colour_)
  22116. {}
  22117. bool operator== (const ColourPoint& other) const noexcept;
  22118. bool operator!= (const ColourPoint& other) const noexcept;
  22119. double position;
  22120. Colour colour;
  22121. };
  22122. Array <ColourPoint> colours;
  22123. JUCE_LEAK_DETECTOR (ColourGradient);
  22124. };
  22125. #endif // __JUCE_COLOURGRADIENT_JUCEHEADER__
  22126. /*** End of inlined file: juce_ColourGradient.h ***/
  22127. /*** Start of inlined file: juce_RectanglePlacement.h ***/
  22128. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  22129. #define __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  22130. /**
  22131. Defines the method used to postion some kind of rectangular object within
  22132. a rectangular viewport.
  22133. Although similar to Justification, this is more specific, and has some extra
  22134. options.
  22135. */
  22136. class JUCE_API RectanglePlacement
  22137. {
  22138. public:
  22139. /** Creates a RectanglePlacement object using a combination of flags. */
  22140. inline RectanglePlacement (int flags_) noexcept : flags (flags_) {}
  22141. /** Creates a copy of another RectanglePlacement object. */
  22142. RectanglePlacement (const RectanglePlacement& other) noexcept;
  22143. /** Copies another RectanglePlacement object. */
  22144. RectanglePlacement& operator= (const RectanglePlacement& other) noexcept;
  22145. bool operator== (const RectanglePlacement& other) const noexcept;
  22146. bool operator!= (const RectanglePlacement& other) const noexcept;
  22147. /** Flag values that can be combined and used in the constructor. */
  22148. enum
  22149. {
  22150. /** Indicates that the source rectangle's left edge should be aligned with the left edge of the target rectangle. */
  22151. xLeft = 1,
  22152. /** Indicates that the source rectangle's right edge should be aligned with the right edge of the target rectangle. */
  22153. xRight = 2,
  22154. /** Indicates that the source should be placed in the centre between the left and right
  22155. sides of the available space. */
  22156. xMid = 4,
  22157. /** Indicates that the source's top edge should be aligned with the top edge of the
  22158. destination rectangle. */
  22159. yTop = 8,
  22160. /** Indicates that the source's bottom edge should be aligned with the bottom edge of the
  22161. destination rectangle. */
  22162. yBottom = 16,
  22163. /** Indicates that the source should be placed in the centre between the top and bottom
  22164. sides of the available space. */
  22165. yMid = 32,
  22166. /** If this flag is set, then the source rectangle will be resized to completely fill
  22167. the destination rectangle, and all other flags are ignored.
  22168. */
  22169. stretchToFit = 64,
  22170. /** If this flag is set, then the source rectangle will be resized so that it is the
  22171. minimum size to completely fill the destination rectangle, without changing its
  22172. aspect ratio. This means that some of the source rectangle may fall outside
  22173. the destination.
  22174. If this flag is not set, the source will be given the maximum size at which none
  22175. of it falls outside the destination rectangle.
  22176. */
  22177. fillDestination = 128,
  22178. /** Indicates that the source rectangle can be reduced in size if required, but should
  22179. never be made larger than its original size.
  22180. */
  22181. onlyReduceInSize = 256,
  22182. /** Indicates that the source rectangle can be enlarged if required, but should
  22183. never be made smaller than its original size.
  22184. */
  22185. onlyIncreaseInSize = 512,
  22186. /** Indicates that the source rectangle's size should be left unchanged.
  22187. */
  22188. doNotResize = (onlyIncreaseInSize | onlyReduceInSize),
  22189. /** A shorthand value that is equivalent to (xMid | yMid). */
  22190. centred = 4 + 32
  22191. };
  22192. /** Returns the raw flags that are set for this object. */
  22193. inline int getFlags() const noexcept { return flags; }
  22194. /** Tests a set of flags for this object.
  22195. @returns true if any of the flags passed in are set on this object.
  22196. */
  22197. inline bool testFlags (int flagsToTest) const noexcept { return (flags & flagsToTest) != 0; }
  22198. /** Adjusts the position and size of a rectangle to fit it into a space.
  22199. The source rectangle co-ordinates will be adjusted so that they fit into
  22200. the destination rectangle based on this object's flags.
  22201. */
  22202. void applyTo (double& sourceX,
  22203. double& sourceY,
  22204. double& sourceW,
  22205. double& sourceH,
  22206. double destinationX,
  22207. double destinationY,
  22208. double destinationW,
  22209. double destinationH) const noexcept;
  22210. /** Returns the transform that should be applied to these source co-ordinates to fit them
  22211. into the destination rectangle using the current flags.
  22212. */
  22213. template <typename ValueType>
  22214. const Rectangle<ValueType> appliedTo (const Rectangle<ValueType>& source,
  22215. const Rectangle<ValueType>& destination) const noexcept
  22216. {
  22217. double x = source.getX(), y = source.getY(), w = source.getWidth(), h = source.getHeight();
  22218. applyTo (x, y, w, h, static_cast <double> (destination.getX()), static_cast <double> (destination.getY()),
  22219. static_cast <double> (destination.getWidth()), static_cast <double> (destination.getHeight()));
  22220. return Rectangle<ValueType> (static_cast <ValueType> (x), static_cast <ValueType> (y),
  22221. static_cast <ValueType> (w), static_cast <ValueType> (h));
  22222. }
  22223. /** Returns the transform that should be applied to these source co-ordinates to fit them
  22224. into the destination rectangle using the current flags.
  22225. */
  22226. const AffineTransform getTransformToFit (const Rectangle<float>& source,
  22227. const Rectangle<float>& destination) const noexcept;
  22228. private:
  22229. int flags;
  22230. };
  22231. #endif // __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  22232. /*** End of inlined file: juce_RectanglePlacement.h ***/
  22233. class LowLevelGraphicsContext;
  22234. class Image;
  22235. class FillType;
  22236. class RectangleList;
  22237. /**
  22238. A graphics context, used for drawing a component or image.
  22239. When a Component needs painting, a Graphics context is passed to its
  22240. Component::paint() method, and this you then call methods within this
  22241. object to actually draw the component's content.
  22242. A Graphics can also be created from an image, to allow drawing directly onto
  22243. that image.
  22244. @see Component::paint
  22245. */
  22246. class JUCE_API Graphics
  22247. {
  22248. public:
  22249. /** Creates a Graphics object to draw directly onto the given image.
  22250. The graphics object that is created will be set up to draw onto the image,
  22251. with the context's clipping area being the entire size of the image, and its
  22252. origin being the image's origin. To draw into a subsection of an image, use the
  22253. reduceClipRegion() and setOrigin() methods.
  22254. Obviously you shouldn't delete the image before this context is deleted.
  22255. */
  22256. explicit Graphics (const Image& imageToDrawOnto);
  22257. /** Destructor. */
  22258. ~Graphics();
  22259. /** Changes the current drawing colour.
  22260. This sets the colour that will now be used for drawing operations - it also
  22261. sets the opacity to that of the colour passed-in.
  22262. If a brush is being used when this method is called, the brush will be deselected,
  22263. and any subsequent drawing will be done with a solid colour brush instead.
  22264. @see setOpacity
  22265. */
  22266. void setColour (const Colour& newColour);
  22267. /** Changes the opacity to use with the current colour.
  22268. If a solid colour is being used for drawing, this changes its opacity
  22269. to this new value (i.e. it doesn't multiply the colour's opacity by this amount).
  22270. If a gradient is being used, this will have no effect on it.
  22271. A value of 0.0 is completely transparent, 1.0 is completely opaque.
  22272. */
  22273. void setOpacity (float newOpacity);
  22274. /** Sets the context to use a gradient for its fill pattern.
  22275. */
  22276. void setGradientFill (const ColourGradient& gradient);
  22277. /** Sets the context to use a tiled image pattern for filling.
  22278. Make sure that you don't delete this image while it's still being used by
  22279. this context!
  22280. */
  22281. void setTiledImageFill (const Image& imageToUse,
  22282. int anchorX, int anchorY,
  22283. float opacity);
  22284. /** Changes the current fill settings.
  22285. @see setColour, setGradientFill, setTiledImageFill
  22286. */
  22287. void setFillType (const FillType& newFill);
  22288. /** Changes the font to use for subsequent text-drawing functions.
  22289. Note there's also a setFont (float, int) method to quickly change the size and
  22290. style of the current font.
  22291. @see drawSingleLineText, drawMultiLineText, drawTextAsPath, drawText, drawFittedText
  22292. */
  22293. void setFont (const Font& newFont);
  22294. /** Changes the size and style of the currently-selected font.
  22295. This is a convenient shortcut that changes the context's current font to a
  22296. different size or style. The typeface won't be changed.
  22297. @see Font
  22298. */
  22299. void setFont (float newFontHeight, int fontStyleFlags = Font::plain);
  22300. /** Returns the currently selected font. */
  22301. Font getCurrentFont() const;
  22302. /** Draws a one-line text string.
  22303. This will use the current colour (or brush) to fill the text. The font is the last
  22304. one specified by setFont().
  22305. @param text the string to draw
  22306. @param startX the position to draw the left-hand edge of the text
  22307. @param baselineY the position of the text's baseline
  22308. @see drawMultiLineText, drawText, drawFittedText, GlyphArrangement::addLineOfText
  22309. */
  22310. void drawSingleLineText (const String& text,
  22311. int startX, int baselineY) const;
  22312. /** Draws text across multiple lines.
  22313. This will break the text onto a new line where there's a new-line or
  22314. carriage-return character, or at a word-boundary when the text becomes wider
  22315. than the size specified by the maximumLineWidth parameter.
  22316. @see setFont, drawSingleLineText, drawFittedText, GlyphArrangement::addJustifiedText
  22317. */
  22318. void drawMultiLineText (const String& text,
  22319. int startX, int baselineY,
  22320. int maximumLineWidth) const;
  22321. /** Renders a string of text as a vector path.
  22322. This allows a string to be transformed with an arbitrary AffineTransform and
  22323. rendered using the current colour/brush. It's much slower than the normal text methods
  22324. but more accurate.
  22325. @see setFont
  22326. */
  22327. void drawTextAsPath (const String& text,
  22328. const AffineTransform& transform) const;
  22329. /** Draws a line of text within a specified rectangle.
  22330. The text will be positioned within the rectangle based on the justification
  22331. flags passed-in. If the string is too long to fit inside the rectangle, it will
  22332. either be truncated or will have ellipsis added to its end (if the useEllipsesIfTooBig
  22333. flag is true).
  22334. @see drawSingleLineText, drawFittedText, drawMultiLineText, GlyphArrangement::addJustifiedText
  22335. */
  22336. void drawText (const String& text,
  22337. int x, int y, int width, int height,
  22338. const Justification& justificationType,
  22339. bool useEllipsesIfTooBig) const;
  22340. /** Tries to draw a text string inside a given space.
  22341. This does its best to make the given text readable within the specified rectangle,
  22342. so it useful for labelling things.
  22343. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  22344. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  22345. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  22346. it's been truncated.
  22347. A Justification parameter lets you specify how the text is laid out within the rectangle,
  22348. both horizontally and vertically.
  22349. The minimumHorizontalScale parameter specifies how much the text can be squashed horizontally
  22350. to try to squeeze it into the space. If you don't want any horizontal scaling to occur, you
  22351. can set this value to 1.0f.
  22352. @see GlyphArrangement::addFittedText
  22353. */
  22354. void drawFittedText (const String& text,
  22355. int x, int y, int width, int height,
  22356. const Justification& justificationFlags,
  22357. int maximumNumberOfLines,
  22358. float minimumHorizontalScale = 0.7f) const;
  22359. /** Fills the context's entire clip region with the current colour or brush.
  22360. (See also the fillAll (const Colour&) method which is a quick way of filling
  22361. it with a given colour).
  22362. */
  22363. void fillAll() const;
  22364. /** Fills the context's entire clip region with a given colour.
  22365. This leaves the context's current colour and brush unchanged, it just
  22366. uses the specified colour temporarily.
  22367. */
  22368. void fillAll (const Colour& colourToUse) const;
  22369. /** Fills a rectangle with the current colour or brush.
  22370. @see drawRect, fillRoundedRectangle
  22371. */
  22372. void fillRect (int x, int y, int width, int height) const;
  22373. /** Fills a rectangle with the current colour or brush. */
  22374. void fillRect (const Rectangle<int>& rectangle) const;
  22375. /** Fills a rectangle with the current colour or brush.
  22376. This uses sub-pixel positioning so is slower than the fillRect method which
  22377. takes integer co-ordinates.
  22378. */
  22379. void fillRect (float x, float y, float width, float height) const;
  22380. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  22381. @see drawRoundedRectangle, Path::addRoundedRectangle
  22382. */
  22383. void fillRoundedRectangle (float x, float y, float width, float height,
  22384. float cornerSize) const;
  22385. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  22386. @see drawRoundedRectangle, Path::addRoundedRectangle
  22387. */
  22388. void fillRoundedRectangle (const Rectangle<float>& rectangle,
  22389. float cornerSize) const;
  22390. /** Fills a rectangle with a checkerboard pattern, alternating between two colours.
  22391. */
  22392. void fillCheckerBoard (const Rectangle<int>& area,
  22393. int checkWidth, int checkHeight,
  22394. const Colour& colour1, const Colour& colour2) const;
  22395. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  22396. The lines are drawn inside the given rectangle, and greater line thicknesses
  22397. extend inwards.
  22398. @see fillRect
  22399. */
  22400. void drawRect (int x, int y, int width, int height,
  22401. int lineThickness = 1) const;
  22402. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  22403. The lines are drawn inside the given rectangle, and greater line thicknesses
  22404. extend inwards.
  22405. @see fillRect
  22406. */
  22407. void drawRect (float x, float y, float width, float height,
  22408. float lineThickness = 1.0f) const;
  22409. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  22410. The lines are drawn inside the given rectangle, and greater line thicknesses
  22411. extend inwards.
  22412. @see fillRect
  22413. */
  22414. void drawRect (const Rectangle<int>& rectangle,
  22415. int lineThickness = 1) const;
  22416. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  22417. @see fillRoundedRectangle, Path::addRoundedRectangle
  22418. */
  22419. void drawRoundedRectangle (float x, float y, float width, float height,
  22420. float cornerSize, float lineThickness) const;
  22421. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  22422. @see fillRoundedRectangle, Path::addRoundedRectangle
  22423. */
  22424. void drawRoundedRectangle (const Rectangle<float>& rectangle,
  22425. float cornerSize, float lineThickness) const;
  22426. /** Draws a 3D raised (or indented) bevel using two colours.
  22427. The bevel is drawn inside the given rectangle, and greater bevel thicknesses
  22428. extend inwards.
  22429. The top-left colour is used for the top- and left-hand edges of the
  22430. bevel; the bottom-right colour is used for the bottom- and right-hand
  22431. edges.
  22432. If useGradient is true, then the bevel fades out to make it look more curved
  22433. and less angular. If sharpEdgeOnOutside is true, the outside of the bevel is
  22434. sharp, and it fades towards the centre; if sharpEdgeOnOutside is false, then
  22435. the centre edges are sharp and it fades towards the outside.
  22436. */
  22437. void drawBevel (int x, int y, int width, int height,
  22438. int bevelThickness,
  22439. const Colour& topLeftColour = Colours::white,
  22440. const Colour& bottomRightColour = Colours::black,
  22441. bool useGradient = true,
  22442. bool sharpEdgeOnOutside = true) const;
  22443. /** Draws a pixel using the current colour or brush.
  22444. */
  22445. void setPixel (int x, int y) const;
  22446. /** Fills an ellipse with the current colour or brush.
  22447. The ellipse is drawn to fit inside the given rectangle.
  22448. @see drawEllipse, Path::addEllipse
  22449. */
  22450. void fillEllipse (float x, float y, float width, float height) const;
  22451. /** Draws an elliptical stroke using the current colour or brush.
  22452. @see fillEllipse, Path::addEllipse
  22453. */
  22454. void drawEllipse (float x, float y, float width, float height,
  22455. float lineThickness) const;
  22456. /** Draws a line between two points.
  22457. The line is 1 pixel wide and drawn with the current colour or brush.
  22458. */
  22459. void drawLine (float startX, float startY, float endX, float endY) const;
  22460. /** Draws a line between two points with a given thickness.
  22461. @see Path::addLineSegment
  22462. */
  22463. void drawLine (float startX, float startY, float endX, float endY,
  22464. float lineThickness) const;
  22465. /** Draws a line between two points.
  22466. The line is 1 pixel wide and drawn with the current colour or brush.
  22467. */
  22468. void drawLine (const Line<float>& line) const;
  22469. /** Draws a line between two points with a given thickness.
  22470. @see Path::addLineSegment
  22471. */
  22472. void drawLine (const Line<float>& line, float lineThickness) const;
  22473. /** Draws a dashed line using a custom set of dash-lengths.
  22474. @param line the line to draw
  22475. @param dashLengths a series of lengths to specify the on/off lengths - e.g.
  22476. { 4, 5, 6, 7 } will draw a line of 4 pixels, skip 5 pixels,
  22477. draw 6 pixels, skip 7 pixels, and then repeat.
  22478. @param numDashLengths the number of elements in the array (this must be an even number).
  22479. @param lineThickness the thickness of the line to draw
  22480. @param dashIndexToStartFrom the index in the dash-length array to use for the first segment
  22481. @see PathStrokeType::createDashedStroke
  22482. */
  22483. void drawDashedLine (const Line<float>& line,
  22484. const float* dashLengths, int numDashLengths,
  22485. float lineThickness = 1.0f,
  22486. int dashIndexToStartFrom = 0) const;
  22487. /** Draws a vertical line of pixels at a given x position.
  22488. The x position is an integer, but the top and bottom of the line can be sub-pixel
  22489. positions, and these will be anti-aliased if necessary.
  22490. The bottom parameter must be greater than or equal to the top parameter.
  22491. */
  22492. void drawVerticalLine (int x, float top, float bottom) const;
  22493. /** Draws a horizontal line of pixels at a given y position.
  22494. The y position is an integer, but the left and right ends of the line can be sub-pixel
  22495. positions, and these will be anti-aliased if necessary.
  22496. The right parameter must be greater than or equal to the left parameter.
  22497. */
  22498. void drawHorizontalLine (int y, float left, float right) const;
  22499. /** Fills a path using the currently selected colour or brush.
  22500. */
  22501. void fillPath (const Path& path,
  22502. const AffineTransform& transform = AffineTransform::identity) const;
  22503. /** Draws a path's outline using the currently selected colour or brush.
  22504. */
  22505. void strokePath (const Path& path,
  22506. const PathStrokeType& strokeType,
  22507. const AffineTransform& transform = AffineTransform::identity) const;
  22508. /** Draws a line with an arrowhead at its end.
  22509. @param line the line to draw
  22510. @param lineThickness the thickness of the line
  22511. @param arrowheadWidth the width of the arrow head (perpendicular to the line)
  22512. @param arrowheadLength the length of the arrow head (along the length of the line)
  22513. */
  22514. void drawArrow (const Line<float>& line,
  22515. float lineThickness,
  22516. float arrowheadWidth,
  22517. float arrowheadLength) const;
  22518. /** Types of rendering quality that can be specified when drawing images.
  22519. @see blendImage, Graphics::setImageResamplingQuality
  22520. */
  22521. enum ResamplingQuality
  22522. {
  22523. lowResamplingQuality = 0, /**< Just uses a nearest-neighbour algorithm for resampling. */
  22524. mediumResamplingQuality = 1, /**< Uses bilinear interpolation for upsampling and area-averaging for downsampling. */
  22525. highResamplingQuality = 2 /**< Uses bicubic interpolation for upsampling and area-averaging for downsampling. */
  22526. };
  22527. /** Changes the quality that will be used when resampling images.
  22528. By default a Graphics object will be set to mediumRenderingQuality.
  22529. @see Graphics::drawImage, Graphics::drawImageTransformed, Graphics::drawImageWithin
  22530. */
  22531. void setImageResamplingQuality (const ResamplingQuality newQuality);
  22532. /** Draws an image.
  22533. This will draw the whole of an image, positioning its top-left corner at the
  22534. given co-ordinates, and keeping its size the same. This is the simplest image
  22535. drawing method - the others give more control over the scaling and clipping
  22536. of the images.
  22537. Images are composited using the context's current opacity, so if you
  22538. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  22539. (or setColour() with an opaque colour) before drawing images.
  22540. */
  22541. void drawImageAt (const Image& imageToDraw, int topLeftX, int topLeftY,
  22542. bool fillAlphaChannelWithCurrentBrush = false) const;
  22543. /** Draws part of an image, rescaling it to fit in a given target region.
  22544. The specified area of the source image is rescaled and drawn to fill the
  22545. specifed destination rectangle.
  22546. Images are composited using the context's current opacity, so if you
  22547. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  22548. (or setColour() with an opaque colour) before drawing images.
  22549. @param imageToDraw the image to overlay
  22550. @param destX the left of the destination rectangle
  22551. @param destY the top of the destination rectangle
  22552. @param destWidth the width of the destination rectangle
  22553. @param destHeight the height of the destination rectangle
  22554. @param sourceX the left of the rectangle to copy from the source image
  22555. @param sourceY the top of the rectangle to copy from the source image
  22556. @param sourceWidth the width of the rectangle to copy from the source image
  22557. @param sourceHeight the height of the rectangle to copy from the source image
  22558. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the source image's pixels,
  22559. the source image's alpha channel is used as a mask with
  22560. which to fill the destination using the current colour
  22561. or brush. (If the source is has no alpha channel, then
  22562. it will just fill the target with a solid rectangle)
  22563. @see setImageResamplingQuality, drawImageAt, drawImageWithin, fillAlphaMap
  22564. */
  22565. void drawImage (const Image& imageToDraw,
  22566. int destX, int destY, int destWidth, int destHeight,
  22567. int sourceX, int sourceY, int sourceWidth, int sourceHeight,
  22568. bool fillAlphaChannelWithCurrentBrush = false) const;
  22569. /** Draws an image, having applied an affine transform to it.
  22570. This lets you throw the image around in some wacky ways, rotate it, shear,
  22571. scale it, etc.
  22572. Images are composited using the context's current opacity, so if you
  22573. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  22574. (or setColour() with an opaque colour) before drawing images.
  22575. If fillAlphaChannelWithCurrentBrush is set to true, then the image's RGB channels
  22576. are ignored and it is filled with the current brush, masked by its alpha channel.
  22577. If you want to render only a subsection of an image, use Image::getClippedImage() to
  22578. create the section that you need.
  22579. @see setImageResamplingQuality, drawImage
  22580. */
  22581. void drawImageTransformed (const Image& imageToDraw,
  22582. const AffineTransform& transform,
  22583. bool fillAlphaChannelWithCurrentBrush = false) const;
  22584. /** Draws an image to fit within a designated rectangle.
  22585. If the image is too big or too small for the space, it will be rescaled
  22586. to fit as nicely as it can do without affecting its aspect ratio. It will
  22587. then be placed within the target rectangle according to the justification flags
  22588. specified.
  22589. @param imageToDraw the source image to draw
  22590. @param destX top-left of the target rectangle to fit it into
  22591. @param destY top-left of the target rectangle to fit it into
  22592. @param destWidth size of the target rectangle to fit the image into
  22593. @param destHeight size of the target rectangle to fit the image into
  22594. @param placementWithinTarget this specifies how the image should be positioned
  22595. within the target rectangle - see the RectanglePlacement
  22596. class for more details about this.
  22597. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the image, just its
  22598. alpha channel will be used as a mask with which to
  22599. draw with the current brush or colour. This is
  22600. similar to fillAlphaMap(), and see also drawImage()
  22601. @see setImageResamplingQuality, drawImage, drawImageTransformed, drawImageAt, RectanglePlacement
  22602. */
  22603. void drawImageWithin (const Image& imageToDraw,
  22604. int destX, int destY, int destWidth, int destHeight,
  22605. const RectanglePlacement& placementWithinTarget,
  22606. bool fillAlphaChannelWithCurrentBrush = false) const;
  22607. /** Returns the position of the bounding box for the current clipping region.
  22608. @see getClipRegion, clipRegionIntersects
  22609. */
  22610. const Rectangle<int> getClipBounds() const;
  22611. /** Checks whether a rectangle overlaps the context's clipping region.
  22612. If this returns false, no part of the given area can be drawn onto, so this
  22613. method can be used to optimise a component's paint() method, by letting it
  22614. avoid drawing complex objects that aren't within the region being repainted.
  22615. */
  22616. bool clipRegionIntersects (const Rectangle<int>& area) const;
  22617. /** Intersects the current clipping region with another region.
  22618. @returns true if the resulting clipping region is non-zero in size
  22619. @see setOrigin, clipRegionIntersects
  22620. */
  22621. bool reduceClipRegion (int x, int y, int width, int height);
  22622. /** Intersects the current clipping region with another region.
  22623. @returns true if the resulting clipping region is non-zero in size
  22624. @see setOrigin, clipRegionIntersects
  22625. */
  22626. bool reduceClipRegion (const Rectangle<int>& area);
  22627. /** Intersects the current clipping region with a rectangle list region.
  22628. @returns true if the resulting clipping region is non-zero in size
  22629. @see setOrigin, clipRegionIntersects
  22630. */
  22631. bool reduceClipRegion (const RectangleList& clipRegion);
  22632. /** Intersects the current clipping region with a path.
  22633. @returns true if the resulting clipping region is non-zero in size
  22634. @see reduceClipRegion
  22635. */
  22636. bool reduceClipRegion (const Path& path, const AffineTransform& transform = AffineTransform::identity);
  22637. /** Intersects the current clipping region with an image's alpha-channel.
  22638. The current clipping path is intersected with the area covered by this image's
  22639. alpha-channel, after the image has been transformed by the specified matrix.
  22640. @param image the image whose alpha-channel should be used. If the image doesn't
  22641. have an alpha-channel, it is treated as entirely opaque.
  22642. @param transform a matrix to apply to the image
  22643. @returns true if the resulting clipping region is non-zero in size
  22644. @see reduceClipRegion
  22645. */
  22646. bool reduceClipRegion (const Image& image, const AffineTransform& transform);
  22647. /** Excludes a rectangle to stop it being drawn into. */
  22648. void excludeClipRegion (const Rectangle<int>& rectangleToExclude);
  22649. /** Returns true if no drawing can be done because the clip region is zero. */
  22650. bool isClipEmpty() const;
  22651. /** Saves the current graphics state on an internal stack.
  22652. To restore the state, use restoreState().
  22653. @see ScopedSaveState
  22654. */
  22655. void saveState();
  22656. /** Restores a graphics state that was previously saved with saveState().
  22657. @see ScopedSaveState
  22658. */
  22659. void restoreState();
  22660. /** Uses RAII to save and restore the state of a graphics context.
  22661. On construction, this calls Graphics::saveState(), and on destruction it calls
  22662. Graphics::restoreState() on the Graphics object that you supply.
  22663. */
  22664. class ScopedSaveState
  22665. {
  22666. public:
  22667. ScopedSaveState (Graphics& g);
  22668. ~ScopedSaveState();
  22669. private:
  22670. Graphics& context;
  22671. JUCE_DECLARE_NON_COPYABLE (ScopedSaveState);
  22672. };
  22673. /** Begins rendering to an off-screen bitmap which will later be flattened onto the current
  22674. context with the given opacity.
  22675. The context uses an internal stack of temporary image layers to do this. When you've
  22676. finished drawing to the layer, call endTransparencyLayer() to complete the operation and
  22677. composite the finished layer. Every call to beginTransparencyLayer() MUST be matched
  22678. by a corresponding call to endTransparencyLayer()!
  22679. This call also saves the current state, and endTransparencyLayer() restores it.
  22680. */
  22681. void beginTransparencyLayer (float layerOpacity);
  22682. /** Completes a drawing operation to a temporary semi-transparent buffer.
  22683. See beginTransparencyLayer() for more details.
  22684. */
  22685. void endTransparencyLayer();
  22686. /** Moves the position of the context's origin.
  22687. This changes the position that the context considers to be (0, 0) to
  22688. the specified position.
  22689. So if you call setOrigin (100, 100), then the position that was previously
  22690. referred to as (100, 100) will subsequently be considered to be (0, 0).
  22691. @see reduceClipRegion, addTransform
  22692. */
  22693. void setOrigin (int newOriginX, int newOriginY);
  22694. /** Adds a transformation which will be performed on all the graphics operations that
  22695. the context subsequently performs.
  22696. After calling this, all the coordinates that are passed into the context will be
  22697. transformed by this matrix.
  22698. @see setOrigin
  22699. */
  22700. void addTransform (const AffineTransform& transform);
  22701. /** Resets the current colour, brush, and font to default settings. */
  22702. void resetToDefaultState();
  22703. /** Returns true if this context is drawing to a vector-based device, such as a printer. */
  22704. bool isVectorDevice() const;
  22705. /** Create a graphics that uses a given low-level renderer.
  22706. For internal use only.
  22707. NB. The context will NOT be deleted by this object when it is deleted.
  22708. */
  22709. Graphics (LowLevelGraphicsContext* internalContext) noexcept;
  22710. /** @internal */
  22711. LowLevelGraphicsContext* getInternalContext() const noexcept { return context; }
  22712. private:
  22713. LowLevelGraphicsContext* const context;
  22714. ScopedPointer <LowLevelGraphicsContext> contextToDelete;
  22715. bool saveStatePending;
  22716. void saveStateIfPending();
  22717. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Graphics);
  22718. };
  22719. #endif // __JUCE_GRAPHICS_JUCEHEADER__
  22720. /*** End of inlined file: juce_Graphics.h ***/
  22721. /**
  22722. A graphical effect filter that can be applied to components.
  22723. An ImageEffectFilter can be applied to the image that a component
  22724. paints before it hits the screen.
  22725. This is used for adding effects like shadows, blurs, etc.
  22726. @see Component::setComponentEffect
  22727. */
  22728. class JUCE_API ImageEffectFilter
  22729. {
  22730. public:
  22731. /** Overridden to render the effect.
  22732. The implementation of this method must use the image that is passed in
  22733. as its source, and should render its output to the graphics context passed in.
  22734. @param sourceImage the image that the source component has just rendered with
  22735. its paint() method. The image may or may not have an alpha
  22736. channel, depending on whether the component is opaque.
  22737. @param destContext the graphics context to use to draw the resultant image.
  22738. @param alpha the alpha with which to draw the resultant image to the
  22739. target context
  22740. */
  22741. virtual void applyEffect (Image& sourceImage,
  22742. Graphics& destContext,
  22743. float alpha) = 0;
  22744. /** Destructor. */
  22745. virtual ~ImageEffectFilter() {}
  22746. };
  22747. #endif // __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  22748. /*** End of inlined file: juce_ImageEffectFilter.h ***/
  22749. /*** Start of inlined file: juce_Image.h ***/
  22750. #ifndef __JUCE_IMAGE_JUCEHEADER__
  22751. #define __JUCE_IMAGE_JUCEHEADER__
  22752. /**
  22753. Holds a fixed-size bitmap.
  22754. The image is stored in either 24-bit RGB or 32-bit premultiplied-ARGB format.
  22755. To draw into an image, create a Graphics object for it.
  22756. e.g. @code
  22757. // create a transparent 500x500 image..
  22758. Image myImage (Image::RGB, 500, 500, true);
  22759. Graphics g (myImage);
  22760. g.setColour (Colours::red);
  22761. g.fillEllipse (20, 20, 300, 200); // draws a red ellipse in our image.
  22762. @endcode
  22763. Other useful ways to create an image are with the ImageCache class, or the
  22764. ImageFileFormat, which provides a way to load common image files.
  22765. @see Graphics, ImageFileFormat, ImageCache, ImageConvolutionKernel
  22766. */
  22767. class JUCE_API Image
  22768. {
  22769. public:
  22770. /**
  22771. */
  22772. enum PixelFormat
  22773. {
  22774. UnknownFormat,
  22775. RGB, /**<< each pixel is a 3-byte packed RGB colour value. For byte order, see the PixelRGB class. */
  22776. ARGB, /**<< each pixel is a 4-byte ARGB premultiplied colour value. For byte order, see the PixelARGB class. */
  22777. SingleChannel /**<< each pixel is a 1-byte alpha channel value. */
  22778. };
  22779. /**
  22780. */
  22781. enum ImageType
  22782. {
  22783. SoftwareImage = 0,
  22784. NativeImage
  22785. };
  22786. /** Creates a null image. */
  22787. Image();
  22788. /** Creates an image with a specified size and format.
  22789. @param format the number of colour channels in the image
  22790. @param imageWidth the desired width of the image, in pixels - this value must be
  22791. greater than zero (otherwise a width of 1 will be used)
  22792. @param imageHeight the desired width of the image, in pixels - this value must be
  22793. greater than zero (otherwise a height of 1 will be used)
  22794. @param clearImage if true, the image will initially be cleared to black (if it's RGB)
  22795. or transparent black (if it's ARGB). If false, the image may contain
  22796. junk initially, so you need to make sure you overwrite it thoroughly.
  22797. @param type the type of image - this lets you specify whether you want a purely
  22798. memory-based image, or one that may be managed by the OS if possible.
  22799. */
  22800. Image (PixelFormat format,
  22801. int imageWidth,
  22802. int imageHeight,
  22803. bool clearImage,
  22804. ImageType type = NativeImage);
  22805. /** Creates a shared reference to another image.
  22806. This won't create a duplicate of the image - when Image objects are copied, they simply
  22807. point to the same shared image data. To make sure that an Image object has its own unique,
  22808. unshared internal data, call duplicateIfShared().
  22809. */
  22810. Image (const Image& other);
  22811. /** Makes this image refer to the same underlying image as another object.
  22812. This won't create a duplicate of the image - when Image objects are copied, they simply
  22813. point to the same shared image data. To make sure that an Image object has its own unique,
  22814. unshared internal data, call duplicateIfShared().
  22815. */
  22816. Image& operator= (const Image&);
  22817. /** Destructor. */
  22818. ~Image();
  22819. /** Returns true if the two images are referring to the same internal, shared image. */
  22820. bool operator== (const Image& other) const noexcept { return image == other.image; }
  22821. /** Returns true if the two images are not referring to the same internal, shared image. */
  22822. bool operator!= (const Image& other) const noexcept { return image != other.image; }
  22823. /** Returns true if this image isn't null.
  22824. If you create an Image with the default constructor, it has no size or content, and is null
  22825. until you reassign it to an Image which contains some actual data.
  22826. The isNull() method is the opposite of isValid().
  22827. @see isNull
  22828. */
  22829. inline bool isValid() const noexcept { return image != nullptr; }
  22830. /** Returns true if this image is not valid.
  22831. If you create an Image with the default constructor, it has no size or content, and is null
  22832. until you reassign it to an Image which contains some actual data.
  22833. The isNull() method is the opposite of isValid().
  22834. @see isValid
  22835. */
  22836. inline bool isNull() const noexcept { return image == nullptr; }
  22837. /** A null Image object that can be used when you need to return an invalid image.
  22838. This object is the equivalient to an Image created with the default constructor.
  22839. */
  22840. static const Image null;
  22841. /** Returns the image's width (in pixels). */
  22842. int getWidth() const noexcept { return image == nullptr ? 0 : image->width; }
  22843. /** Returns the image's height (in pixels). */
  22844. int getHeight() const noexcept { return image == nullptr ? 0 : image->height; }
  22845. /** Returns a rectangle with the same size as this image.
  22846. The rectangle's origin is always (0, 0).
  22847. */
  22848. const Rectangle<int> getBounds() const noexcept { return image == nullptr ? Rectangle<int>() : Rectangle<int> (image->width, image->height); }
  22849. /** Returns the image's pixel format. */
  22850. PixelFormat getFormat() const noexcept { return image == nullptr ? UnknownFormat : image->format; }
  22851. /** True if the image's format is ARGB. */
  22852. bool isARGB() const noexcept { return getFormat() == ARGB; }
  22853. /** True if the image's format is RGB. */
  22854. bool isRGB() const noexcept { return getFormat() == RGB; }
  22855. /** True if the image's format is a single-channel alpha map. */
  22856. bool isSingleChannel() const noexcept { return getFormat() == SingleChannel; }
  22857. /** True if the image contains an alpha-channel. */
  22858. bool hasAlphaChannel() const noexcept { return getFormat() != RGB; }
  22859. /** Clears a section of the image with a given colour.
  22860. This won't do any alpha-blending - it just sets all pixels in the image to
  22861. the given colour (which may be non-opaque if the image has an alpha channel).
  22862. */
  22863. void clear (const Rectangle<int>& area, const Colour& colourToClearTo = Colour (0x00000000));
  22864. /** Returns a rescaled version of this image.
  22865. A new image is returned which is a copy of this one, rescaled to the given size.
  22866. Note that if the new size is identical to the existing image, this will just return
  22867. a reference to the original image, and won't actually create a duplicate.
  22868. */
  22869. Image rescaled (int newWidth, int newHeight,
  22870. Graphics::ResamplingQuality quality = Graphics::mediumResamplingQuality) const;
  22871. /** Returns a version of this image with a different image format.
  22872. A new image is returned which has been converted to the specified format.
  22873. Note that if the new format is no different to the current one, this will just return
  22874. a reference to the original image, and won't actually create a copy.
  22875. */
  22876. Image convertedToFormat (PixelFormat newFormat) const;
  22877. /** Makes sure that no other Image objects share the same underlying data as this one.
  22878. If no other Image objects refer to the same shared data as this one, this method has no
  22879. effect. But if there are other references to the data, this will create a new copy of
  22880. the data internally.
  22881. Call this if you want to draw onto the image, but want to make sure that this doesn't
  22882. affect any other code that may be sharing the same data.
  22883. @see getReferenceCount
  22884. */
  22885. void duplicateIfShared();
  22886. /** Returns an image which refers to a subsection of this image.
  22887. This will not make a copy of the original - the new image will keep a reference to it, so that
  22888. if the original image is changed, the contents of the subsection will also change. Likewise if you
  22889. draw into the subimage, you'll also be drawing onto that area of the original image. Note that if
  22890. you use operator= to make the original Image object refer to something else, the subsection image
  22891. won't pick up this change, it'll remain pointing at the original.
  22892. The area passed-in will be clipped to the bounds of this image, so this may return a smaller
  22893. image than the area you asked for, or even a null image if the area was out-of-bounds.
  22894. */
  22895. Image getClippedImage (const Rectangle<int>& area) const;
  22896. /** Returns the colour of one of the pixels in the image.
  22897. If the co-ordinates given are beyond the image's boundaries, this will
  22898. return Colours::transparentBlack.
  22899. @see setPixelAt, Image::BitmapData::getPixelColour
  22900. */
  22901. const Colour getPixelAt (int x, int y) const;
  22902. /** Sets the colour of one of the image's pixels.
  22903. If the co-ordinates are beyond the image's boundaries, then nothing will happen.
  22904. Note that this won't do any alpha-blending, it'll just replace the existing pixel
  22905. with the given one. The colour's opacity will be ignored if this image doesn't have
  22906. an alpha-channel.
  22907. @see getPixelAt, Image::BitmapData::setPixelColour
  22908. */
  22909. void setPixelAt (int x, int y, const Colour& colour);
  22910. /** Changes the opacity of a pixel.
  22911. This only has an effect if the image has an alpha channel and if the
  22912. given co-ordinates are inside the image's boundary.
  22913. The multiplier must be in the range 0 to 1.0, and the current alpha
  22914. at the given co-ordinates will be multiplied by this value.
  22915. @see setPixelAt
  22916. */
  22917. void multiplyAlphaAt (int x, int y, float multiplier);
  22918. /** Changes the overall opacity of the image.
  22919. This will multiply the alpha value of each pixel in the image by the given
  22920. amount (limiting the resulting alpha values between 0 and 255). This allows
  22921. you to make an image more or less transparent.
  22922. If the image doesn't have an alpha channel, this won't have any effect.
  22923. */
  22924. void multiplyAllAlphas (float amountToMultiplyBy);
  22925. /** Changes all the colours to be shades of grey, based on their current luminosity.
  22926. */
  22927. void desaturate();
  22928. /** Retrieves a section of an image as raw pixel data, so it can be read or written to.
  22929. You should only use this class as a last resort - messing about with the internals of
  22930. an image is only recommended for people who really know what they're doing!
  22931. A BitmapData object should be used as a temporary, stack-based object. Don't keep one
  22932. hanging around while the image is being used elsewhere.
  22933. Depending on the way the image class is implemented, this may create a temporary buffer
  22934. which is copied back to the image when the object is deleted, or it may just get a pointer
  22935. directly into the image's raw data.
  22936. You can use the stride and data values in this class directly, but don't alter them!
  22937. The actual format of the pixel data depends on the image's format - see Image::getFormat(),
  22938. and the PixelRGB, PixelARGB and PixelAlpha classes for more info.
  22939. */
  22940. class BitmapData
  22941. {
  22942. public:
  22943. enum ReadWriteMode
  22944. {
  22945. readOnly,
  22946. writeOnly,
  22947. readWrite
  22948. };
  22949. BitmapData (Image& image, int x, int y, int w, int h, ReadWriteMode mode);
  22950. BitmapData (const Image& image, int x, int y, int w, int h);
  22951. BitmapData (const Image& image, ReadWriteMode mode);
  22952. ~BitmapData();
  22953. /** Returns a pointer to the start of a line in the image.
  22954. The co-ordinate you provide here isn't checked, so it's the caller's responsibility to make
  22955. sure it's not out-of-range.
  22956. */
  22957. inline uint8* getLinePointer (int y) const noexcept { return data + y * lineStride; }
  22958. /** Returns a pointer to a pixel in the image.
  22959. The co-ordinates you give here are not checked, so it's the caller's responsibility to make sure they're
  22960. not out-of-range.
  22961. */
  22962. inline uint8* getPixelPointer (int x, int y) const noexcept { return data + y * lineStride + x * pixelStride; }
  22963. /** Returns the colour of a given pixel.
  22964. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  22965. repsonsibility to make sure they're within the image's size.
  22966. */
  22967. const Colour getPixelColour (int x, int y) const noexcept;
  22968. /** Sets the colour of a given pixel.
  22969. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  22970. repsonsibility to make sure they're within the image's size.
  22971. */
  22972. void setPixelColour (int x, int y, const Colour& colour) const noexcept;
  22973. uint8* data;
  22974. PixelFormat pixelFormat;
  22975. int lineStride, pixelStride, width, height;
  22976. /** Used internally by custom image types to manage pixel data lifetime. */
  22977. class BitmapDataReleaser
  22978. {
  22979. protected:
  22980. BitmapDataReleaser() {}
  22981. public:
  22982. virtual ~BitmapDataReleaser() {}
  22983. };
  22984. ScopedPointer<BitmapDataReleaser> dataReleaser;
  22985. private:
  22986. JUCE_DECLARE_NON_COPYABLE (BitmapData);
  22987. };
  22988. /** Copies some pixel values to a rectangle of the image.
  22989. The format of the pixel data must match that of the image itself, and the
  22990. rectangle supplied must be within the image's bounds.
  22991. */
  22992. void setPixelData (int destX, int destY, int destW, int destH,
  22993. const uint8* sourcePixelData, int sourceLineStride);
  22994. /** Copies a section of the image to somewhere else within itself. */
  22995. void moveImageSection (int destX, int destY,
  22996. int sourceX, int sourceY,
  22997. int width, int height);
  22998. /** Creates a RectangleList containing rectangles for all non-transparent pixels
  22999. of the image.
  23000. @param result the list that will have the area added to it
  23001. @param alphaThreshold for a semi-transparent image, any pixels whose alpha is
  23002. above this level will be considered opaque
  23003. */
  23004. void createSolidAreaMask (RectangleList& result,
  23005. float alphaThreshold = 0.5f) const;
  23006. /** Returns a NamedValueSet that is attached to the image and which can be used for
  23007. associating custom values with it.
  23008. If this is a null image, this will return a null pointer.
  23009. */
  23010. NamedValueSet* getProperties() const;
  23011. /** Creates a context suitable for drawing onto this image.
  23012. Don't call this method directly! It's used internally by the Graphics class.
  23013. */
  23014. LowLevelGraphicsContext* createLowLevelContext() const;
  23015. /** Returns the number of Image objects which are currently referring to the same internal
  23016. shared image data.
  23017. @see duplicateIfShared
  23018. */
  23019. int getReferenceCount() const noexcept { return image == nullptr ? 0 : image->getReferenceCount(); }
  23020. /** This is a base class for task-specific types of image.
  23021. Don't use this class directly! It's used internally by the Image class.
  23022. */
  23023. class SharedImage : public ReferenceCountedObject
  23024. {
  23025. public:
  23026. SharedImage (PixelFormat format, int width, int height);
  23027. ~SharedImage();
  23028. virtual LowLevelGraphicsContext* createLowLevelContext() = 0;
  23029. virtual SharedImage* clone() = 0;
  23030. virtual ImageType getType() const = 0;
  23031. virtual void initialiseBitmapData (BitmapData& bitmapData, int x, int y, BitmapData::ReadWriteMode mode) = 0;
  23032. static SharedImage* createNativeImage (PixelFormat format, int width, int height, bool clearImage);
  23033. static SharedImage* createSoftwareImage (PixelFormat format, int width, int height, bool clearImage);
  23034. const PixelFormat getPixelFormat() const noexcept { return format; }
  23035. int getWidth() const noexcept { return width; }
  23036. int getHeight() const noexcept { return height; }
  23037. protected:
  23038. friend class Image;
  23039. friend class BitmapData;
  23040. const PixelFormat format;
  23041. const int width, height;
  23042. NamedValueSet userData;
  23043. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SharedImage);
  23044. };
  23045. /** @internal */
  23046. SharedImage* getSharedImage() const noexcept { return image; }
  23047. /** @internal */
  23048. explicit Image (SharedImage* instance);
  23049. private:
  23050. friend class SharedImage;
  23051. friend class BitmapData;
  23052. ReferenceCountedObjectPtr<SharedImage> image;
  23053. JUCE_LEAK_DETECTOR (Image);
  23054. };
  23055. #endif // __JUCE_IMAGE_JUCEHEADER__
  23056. /*** End of inlined file: juce_Image.h ***/
  23057. /*** Start of inlined file: juce_RectangleList.h ***/
  23058. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  23059. #define __JUCE_RECTANGLELIST_JUCEHEADER__
  23060. /**
  23061. Maintains a set of rectangles as a complex region.
  23062. This class allows a set of rectangles to be treated as a solid shape, and can
  23063. add and remove rectangular sections of it, and simplify overlapping or
  23064. adjacent rectangles.
  23065. @see Rectangle
  23066. */
  23067. class JUCE_API RectangleList
  23068. {
  23069. public:
  23070. /** Creates an empty RectangleList */
  23071. RectangleList() noexcept;
  23072. /** Creates a copy of another list */
  23073. RectangleList (const RectangleList& other);
  23074. /** Creates a list containing just one rectangle. */
  23075. RectangleList (const Rectangle<int>& rect);
  23076. /** Copies this list from another one. */
  23077. RectangleList& operator= (const RectangleList& other);
  23078. /** Destructor. */
  23079. ~RectangleList();
  23080. /** Returns true if the region is empty. */
  23081. bool isEmpty() const noexcept;
  23082. /** Returns the number of rectangles in the list. */
  23083. int getNumRectangles() const noexcept { return rects.size(); }
  23084. /** Returns one of the rectangles at a particular index.
  23085. @returns the rectangle at the index, or an empty rectangle if the
  23086. index is out-of-range.
  23087. */
  23088. Rectangle<int> getRectangle (int index) const noexcept;
  23089. /** Removes all rectangles to leave an empty region. */
  23090. void clear();
  23091. /** Merges a new rectangle into the list.
  23092. The rectangle being added will first be clipped to remove any parts of it
  23093. that overlap existing rectangles in the list.
  23094. */
  23095. void add (int x, int y, int width, int height);
  23096. /** Merges a new rectangle into the list.
  23097. The rectangle being added will first be clipped to remove any parts of it
  23098. that overlap existing rectangles in the list, and adjacent rectangles will be
  23099. merged into it.
  23100. */
  23101. void add (const Rectangle<int>& rect);
  23102. /** Dumbly adds a rectangle to the list without checking for overlaps.
  23103. This simply adds the rectangle to the end, it doesn't merge it or remove
  23104. any overlapping bits.
  23105. */
  23106. void addWithoutMerging (const Rectangle<int>& rect);
  23107. /** Merges another rectangle list into this one.
  23108. Any overlaps between the two lists will be clipped, so that the result is
  23109. the union of both lists.
  23110. */
  23111. void add (const RectangleList& other);
  23112. /** Removes a rectangular region from the list.
  23113. Any rectangles in the list which overlap this will be clipped and subdivided
  23114. if necessary.
  23115. */
  23116. void subtract (const Rectangle<int>& rect);
  23117. /** Removes all areas in another RectangleList from this one.
  23118. Any rectangles in the list which overlap this will be clipped and subdivided
  23119. if necessary.
  23120. @returns true if the resulting list is non-empty.
  23121. */
  23122. bool subtract (const RectangleList& otherList);
  23123. /** Removes any areas of the region that lie outside a given rectangle.
  23124. Any rectangles in the list which overlap this will be clipped and subdivided
  23125. if necessary.
  23126. Returns true if the resulting region is not empty, false if it is empty.
  23127. @see getIntersectionWith
  23128. */
  23129. bool clipTo (const Rectangle<int>& rect);
  23130. /** Removes any areas of the region that lie outside a given rectangle list.
  23131. Any rectangles in this object which overlap the specified list will be clipped
  23132. and subdivided if necessary.
  23133. Returns true if the resulting region is not empty, false if it is empty.
  23134. @see getIntersectionWith
  23135. */
  23136. bool clipTo (const RectangleList& other);
  23137. /** Creates a region which is the result of clipping this one to a given rectangle.
  23138. Unlike the other clipTo method, this one doesn't affect this object - it puts the
  23139. resulting region into the list whose reference is passed-in.
  23140. Returns true if the resulting region is not empty, false if it is empty.
  23141. @see clipTo
  23142. */
  23143. bool getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const;
  23144. /** Swaps the contents of this and another list.
  23145. This swaps their internal pointers, so is hugely faster than using copy-by-value
  23146. to swap them.
  23147. */
  23148. void swapWith (RectangleList& otherList) noexcept;
  23149. /** Checks whether the region contains a given point.
  23150. @returns true if the point lies within one of the rectangles in the list
  23151. */
  23152. bool containsPoint (int x, int y) const noexcept;
  23153. /** Checks whether the region contains the whole of a given rectangle.
  23154. @returns true all parts of the rectangle passed in lie within the region
  23155. defined by this object
  23156. @see intersectsRectangle, containsPoint
  23157. */
  23158. bool containsRectangle (const Rectangle<int>& rectangleToCheck) const;
  23159. /** Checks whether the region contains any part of a given rectangle.
  23160. @returns true if any part of the rectangle passed in lies within the region
  23161. defined by this object
  23162. @see containsRectangle
  23163. */
  23164. bool intersectsRectangle (const Rectangle<int>& rectangleToCheck) const noexcept;
  23165. /** Checks whether this region intersects any part of another one.
  23166. @see intersectsRectangle
  23167. */
  23168. bool intersects (const RectangleList& other) const noexcept;
  23169. /** Returns the smallest rectangle that can enclose the whole of this region. */
  23170. Rectangle<int> getBounds() const noexcept;
  23171. /** Optimises the list into a minimum number of constituent rectangles.
  23172. This will try to combine any adjacent rectangles into larger ones where
  23173. possible, to simplify lists that might have been fragmented by repeated
  23174. add/subtract calls.
  23175. */
  23176. void consolidate();
  23177. /** Adds an x and y value to all the co-ordinates. */
  23178. void offsetAll (int dx, int dy) noexcept;
  23179. /** Creates a Path object to represent this region. */
  23180. Path toPath() const;
  23181. /** An iterator for accessing all the rectangles in a RectangleList. */
  23182. class JUCE_API Iterator
  23183. {
  23184. public:
  23185. Iterator (const RectangleList& list) noexcept;
  23186. ~Iterator();
  23187. /** Advances to the next rectangle, and returns true if it's not finished.
  23188. Call this before using getRectangle() to find the rectangle that was returned.
  23189. */
  23190. bool next() noexcept;
  23191. /** Returns the current rectangle. */
  23192. const Rectangle<int>* getRectangle() const noexcept { return current; }
  23193. private:
  23194. const Rectangle<int>* current;
  23195. const RectangleList& owner;
  23196. int index;
  23197. JUCE_DECLARE_NON_COPYABLE (Iterator);
  23198. };
  23199. private:
  23200. friend class Iterator;
  23201. Array <Rectangle<int> > rects;
  23202. JUCE_LEAK_DETECTOR (RectangleList);
  23203. };
  23204. #endif // __JUCE_RECTANGLELIST_JUCEHEADER__
  23205. /*** End of inlined file: juce_RectangleList.h ***/
  23206. /*** Start of inlined file: juce_BorderSize.h ***/
  23207. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  23208. #define __JUCE_BORDERSIZE_JUCEHEADER__
  23209. /**
  23210. Specifies a set of gaps to be left around the sides of a rectangle.
  23211. This is basically the size of the spaces at the top, bottom, left and right of
  23212. a rectangle. It's used by various component classes to specify borders.
  23213. @see Rectangle
  23214. */
  23215. template <typename ValueType>
  23216. class BorderSize
  23217. {
  23218. public:
  23219. /** Creates a null border.
  23220. All sizes are left as 0.
  23221. */
  23222. BorderSize() noexcept
  23223. : top(), left(), bottom(), right()
  23224. {
  23225. }
  23226. /** Creates a copy of another border. */
  23227. BorderSize (const BorderSize& other) noexcept
  23228. : top (other.top), left (other.left), bottom (other.bottom), right (other.right)
  23229. {
  23230. }
  23231. /** Creates a border with the given gaps. */
  23232. BorderSize (ValueType topGap, ValueType leftGap, ValueType bottomGap, ValueType rightGap) noexcept
  23233. : top (topGap), left (leftGap), bottom (bottomGap), right (rightGap)
  23234. {
  23235. }
  23236. /** Creates a border with the given gap on all sides. */
  23237. explicit BorderSize (ValueType allGaps) noexcept
  23238. : top (allGaps), left (allGaps), bottom (allGaps), right (allGaps)
  23239. {
  23240. }
  23241. /** Returns the gap that should be left at the top of the region. */
  23242. ValueType getTop() const noexcept { return top; }
  23243. /** Returns the gap that should be left at the top of the region. */
  23244. ValueType getLeft() const noexcept { return left; }
  23245. /** Returns the gap that should be left at the top of the region. */
  23246. ValueType getBottom() const noexcept { return bottom; }
  23247. /** Returns the gap that should be left at the top of the region. */
  23248. ValueType getRight() const noexcept { return right; }
  23249. /** Returns the sum of the top and bottom gaps. */
  23250. ValueType getTopAndBottom() const noexcept { return top + bottom; }
  23251. /** Returns the sum of the left and right gaps. */
  23252. ValueType getLeftAndRight() const noexcept { return left + right; }
  23253. /** Returns true if this border has no thickness along any edge. */
  23254. bool isEmpty() const noexcept { return left + right + top + bottom == ValueType(); }
  23255. /** Changes the top gap. */
  23256. void setTop (ValueType newTopGap) noexcept { top = newTopGap; }
  23257. /** Changes the left gap. */
  23258. void setLeft (ValueType newLeftGap) noexcept { left = newLeftGap; }
  23259. /** Changes the bottom gap. */
  23260. void setBottom (ValueType newBottomGap) noexcept { bottom = newBottomGap; }
  23261. /** Changes the right gap. */
  23262. void setRight (ValueType newRightGap) noexcept { right = newRightGap; }
  23263. /** Returns a rectangle with these borders removed from it. */
  23264. Rectangle<ValueType> subtractedFrom (const Rectangle<ValueType>& original) const noexcept
  23265. {
  23266. return Rectangle<ValueType> (original.getX() + left,
  23267. original.getY() + top,
  23268. original.getWidth() - (left + right),
  23269. original.getHeight() - (top + bottom));
  23270. }
  23271. /** Removes this border from a given rectangle. */
  23272. void subtractFrom (Rectangle<ValueType>& rectangle) const noexcept
  23273. {
  23274. rectangle = subtractedFrom (rectangle);
  23275. }
  23276. /** Returns a rectangle with these borders added around it. */
  23277. Rectangle<ValueType> addedTo (const Rectangle<ValueType>& original) const noexcept
  23278. {
  23279. return Rectangle<ValueType> (original.getX() - left,
  23280. original.getY() - top,
  23281. original.getWidth() + (left + right),
  23282. original.getHeight() + (top + bottom));
  23283. }
  23284. /** Adds this border around a given rectangle. */
  23285. void addTo (Rectangle<ValueType>& rectangle) const noexcept
  23286. {
  23287. rectangle = addedTo (rectangle);
  23288. }
  23289. bool operator== (const BorderSize& other) const noexcept
  23290. {
  23291. return top == other.top && left == other.left && bottom == other.bottom && right == other.right;
  23292. }
  23293. bool operator!= (const BorderSize& other) const noexcept
  23294. {
  23295. return ! operator== (other);
  23296. }
  23297. private:
  23298. ValueType top, left, bottom, right;
  23299. JUCE_LEAK_DETECTOR (BorderSize);
  23300. };
  23301. #endif // __JUCE_BORDERSIZE_JUCEHEADER__
  23302. /*** End of inlined file: juce_BorderSize.h ***/
  23303. /*** Start of inlined file: juce_ModalComponentManager.h ***/
  23304. #ifndef __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  23305. #define __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  23306. /*** Start of inlined file: juce_DeletedAtShutdown.h ***/
  23307. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  23308. #define __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  23309. /**
  23310. Classes derived from this will be automatically deleted when the application exits.
  23311. After JUCEApplication::shutdown() has been called, any objects derived from
  23312. DeletedAtShutdown which are still in existence will be deleted in the reverse
  23313. order to that in which they were created.
  23314. So if you've got a singleton and don't want to have to explicitly delete it, just
  23315. inherit from this and it'll be taken care of.
  23316. */
  23317. class JUCE_API DeletedAtShutdown
  23318. {
  23319. protected:
  23320. /** Creates a DeletedAtShutdown object. */
  23321. DeletedAtShutdown();
  23322. /** Destructor.
  23323. It's ok to delete these objects explicitly - it's only the ones left
  23324. dangling at the end that will be deleted automatically.
  23325. */
  23326. virtual ~DeletedAtShutdown();
  23327. public:
  23328. /** Deletes all extant objects.
  23329. This shouldn't be used by applications, as it's called automatically
  23330. in the shutdown code of the JUCEApplication class.
  23331. */
  23332. static void deleteAll();
  23333. private:
  23334. static Array <DeletedAtShutdown*>& getObjects();
  23335. JUCE_DECLARE_NON_COPYABLE (DeletedAtShutdown);
  23336. };
  23337. #endif // __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  23338. /*** End of inlined file: juce_DeletedAtShutdown.h ***/
  23339. /**
  23340. Manages the system's stack of modal components.
  23341. Normally you'll just use the Component methods to invoke modal states in components,
  23342. and won't have to deal with this class directly, but this is the singleton object that's
  23343. used internally to manage the stack.
  23344. @see Component::enterModalState, Component::exitModalState, Component::isCurrentlyModal,
  23345. Component::getCurrentlyModalComponent, Component::isCurrentlyBlockedByAnotherModalComponent
  23346. */
  23347. class JUCE_API ModalComponentManager : public AsyncUpdater,
  23348. public DeletedAtShutdown
  23349. {
  23350. public:
  23351. /** Receives callbacks when a modal component is dismissed.
  23352. You can register a callback using Component::enterModalState() or
  23353. ModalComponentManager::attachCallback().
  23354. For some quick ways of creating callback objects, see the ModalCallbackFunction class.
  23355. @see ModalCallbackFunction
  23356. */
  23357. class Callback
  23358. {
  23359. public:
  23360. /** */
  23361. Callback() {}
  23362. /** Destructor. */
  23363. virtual ~Callback() {}
  23364. /** Called to indicate that a modal component has been dismissed.
  23365. You can register a callback using Component::enterModalState() or
  23366. ModalComponentManager::attachCallback().
  23367. The returnValue parameter is the value that was passed to Component::exitModalState()
  23368. when the component was dismissed.
  23369. The callback object will be deleted shortly after this method is called.
  23370. */
  23371. virtual void modalStateFinished (int returnValue) = 0;
  23372. };
  23373. /** Returns the number of components currently being shown modally.
  23374. @see getModalComponent
  23375. */
  23376. int getNumModalComponents() const;
  23377. /** Returns one of the components being shown modally.
  23378. An index of 0 is the most recently-shown, topmost component.
  23379. */
  23380. Component* getModalComponent (int index) const;
  23381. /** Returns true if the specified component is in a modal state. */
  23382. bool isModal (Component* component) const;
  23383. /** Returns true if the specified component is currently the topmost modal component. */
  23384. bool isFrontModalComponent (Component* component) const;
  23385. /** Adds a new callback that will be called when the specified modal component is dismissed.
  23386. If the component is modal, then when it is dismissed, either by being hidden, or by calling
  23387. Component::exitModalState(), then the Callback::modalStateFinished() method will be
  23388. called.
  23389. Each component can have any number of callbacks associated with it, and this one is added
  23390. to that list.
  23391. The object that is passed in will be deleted by the manager when it's no longer needed. If
  23392. the given component is not currently modal, the callback object is deleted immediately and
  23393. no action is taken.
  23394. */
  23395. void attachCallback (Component* component, Callback* callback);
  23396. /** Brings any modal components to the front. */
  23397. void bringModalComponentsToFront (bool topOneShouldGrabFocus = true);
  23398. #if JUCE_MODAL_LOOPS_PERMITTED
  23399. /** Runs the event loop until the currently topmost modal component is dismissed, and
  23400. returns the exit code for that component.
  23401. */
  23402. int runEventLoopForCurrentComponent();
  23403. #endif
  23404. juce_DeclareSingleton_SingleThreaded_Minimal (ModalComponentManager);
  23405. protected:
  23406. /** Creates a ModalComponentManager.
  23407. You shouldn't ever call the constructor - it's a singleton, so use ModalComponentManager::getInstance()
  23408. */
  23409. ModalComponentManager();
  23410. /** Destructor. */
  23411. ~ModalComponentManager();
  23412. /** @internal */
  23413. void handleAsyncUpdate();
  23414. private:
  23415. class ModalItem;
  23416. class ReturnValueRetriever;
  23417. friend class Component;
  23418. friend class OwnedArray <ModalItem>;
  23419. OwnedArray <ModalItem> stack;
  23420. void startModal (Component* component);
  23421. void endModal (Component* component, int returnValue);
  23422. void endModal (Component* component);
  23423. JUCE_DECLARE_NON_COPYABLE (ModalComponentManager);
  23424. };
  23425. /**
  23426. This class provides some handy utility methods for creating ModalComponentManager::Callback
  23427. objects that will invoke a static function with some parameters when a modal component is dismissed.
  23428. */
  23429. class ModalCallbackFunction
  23430. {
  23431. public:
  23432. /** This is a utility function to create a ModalComponentManager::Callback that will
  23433. call a static function with a parameter.
  23434. The function that you supply must take two parameters - the first being an int, which is
  23435. the result code that was used when the modal component was dismissed, and the second
  23436. can be a custom type. Note that this custom value will be copied and stored, so it must
  23437. be a primitive type or a class that provides copy-by-value semantics.
  23438. E.g. @code
  23439. static void myCallbackFunction (int modalResult, double customValue)
  23440. {
  23441. if (modalResult == 1)
  23442. doSomethingWith (customValue);
  23443. }
  23444. Component* someKindOfComp;
  23445. ...
  23446. someKindOfComp->enterModalState (ModalCallbackFunction::create (myCallbackFunction, 3.0));
  23447. @endcode
  23448. @see ModalComponentManager::Callback
  23449. */
  23450. template <typename ParamType>
  23451. static ModalComponentManager::Callback* create (void (*functionToCall) (int, ParamType),
  23452. ParamType parameterValue)
  23453. {
  23454. return new FunctionCaller1 <ParamType> (functionToCall, parameterValue);
  23455. }
  23456. /** This is a utility function to create a ModalComponentManager::Callback that will
  23457. call a static function with two custom parameters.
  23458. The function that you supply must take three parameters - the first being an int, which is
  23459. the result code that was used when the modal component was dismissed, and the next two are
  23460. your custom types. Note that these custom values will be copied and stored, so they must
  23461. be primitive types or classes that provide copy-by-value semantics.
  23462. E.g. @code
  23463. static void myCallbackFunction (int modalResult, double customValue1, String customValue2)
  23464. {
  23465. if (modalResult == 1)
  23466. doSomethingWith (customValue1, customValue2);
  23467. }
  23468. Component* someKindOfComp;
  23469. ...
  23470. someKindOfComp->enterModalState (ModalCallbackFunction::create (myCallbackFunction, 3.0, String ("xyz")));
  23471. @endcode
  23472. @see ModalComponentManager::Callback
  23473. */
  23474. template <typename ParamType1, typename ParamType2>
  23475. static ModalComponentManager::Callback* withParam (void (*functionToCall) (int, ParamType1, ParamType2),
  23476. ParamType1 parameterValue1,
  23477. ParamType2 parameterValue2)
  23478. {
  23479. return new FunctionCaller2 <ParamType1, ParamType2> (functionToCall, parameterValue1, parameterValue2);
  23480. }
  23481. /** This is a utility function to create a ModalComponentManager::Callback that will
  23482. call a static function with a component.
  23483. The function that you supply must take two parameters - the first being an int, which is
  23484. the result code that was used when the modal component was dismissed, and the second
  23485. can be a Component class. The component will be stored as a WeakReference, so that if it gets
  23486. deleted before this callback is invoked, the pointer that is passed to the function will be null.
  23487. E.g. @code
  23488. static void myCallbackFunction (int modalResult, Slider* mySlider)
  23489. {
  23490. if (modalResult == 1 && mySlider != nullptr) // (must check that mySlider isn't null in case it was deleted..)
  23491. mySlider->setValue (0.0);
  23492. }
  23493. Component* someKindOfComp;
  23494. Slider* mySlider;
  23495. ...
  23496. someKindOfComp->enterModalState (ModalCallbackFunction::forComponent (myCallbackFunction, mySlider));
  23497. @endcode
  23498. @see ModalComponentManager::Callback
  23499. */
  23500. template <class ComponentType>
  23501. static ModalComponentManager::Callback* forComponent (void (*functionToCall) (int, ComponentType*),
  23502. ComponentType* component)
  23503. {
  23504. return new ComponentCaller1 <ComponentType> (functionToCall, component);
  23505. }
  23506. /** Creates a ModalComponentManager::Callback that will call a static function with a component.
  23507. The function that you supply must take three parameters - the first being an int, which is
  23508. the result code that was used when the modal component was dismissed, the second being a Component
  23509. class, and the third being a custom type (which must be a primitive type or have copy-by-value semantics).
  23510. The component will be stored as a WeakReference, so that if it gets deleted before this callback is
  23511. invoked, the pointer that is passed into the function will be null.
  23512. E.g. @code
  23513. static void myCallbackFunction (int modalResult, Slider* mySlider, String customParam)
  23514. {
  23515. if (modalResult == 1 && mySlider != nullptr) // (must check that mySlider isn't null in case it was deleted..)
  23516. mySlider->setName (customParam);
  23517. }
  23518. Component* someKindOfComp;
  23519. Slider* mySlider;
  23520. ...
  23521. someKindOfComp->enterModalState (ModalCallbackFunction::forComponent (myCallbackFunction, mySlider, String ("hello")));
  23522. @endcode
  23523. @see ModalComponentManager::Callback
  23524. */
  23525. template <class ComponentType, typename ParamType>
  23526. static ModalComponentManager::Callback* forComponent (void (*functionToCall) (int, ComponentType*, ParamType),
  23527. ComponentType* component,
  23528. ParamType param)
  23529. {
  23530. return new ComponentCaller2 <ComponentType, ParamType> (functionToCall, component, param);
  23531. }
  23532. private:
  23533. template <typename ParamType>
  23534. class FunctionCaller1 : public ModalComponentManager::Callback
  23535. {
  23536. public:
  23537. typedef void (*FunctionType) (int, ParamType);
  23538. FunctionCaller1 (FunctionType& function_, ParamType& param_)
  23539. : function (function_), param (param_) {}
  23540. void modalStateFinished (int returnValue) { function (returnValue, param); }
  23541. private:
  23542. const FunctionType function;
  23543. ParamType param;
  23544. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FunctionCaller1);
  23545. };
  23546. template <typename ParamType1, typename ParamType2>
  23547. class FunctionCaller2 : public ModalComponentManager::Callback
  23548. {
  23549. public:
  23550. typedef void (*FunctionType) (int, ParamType1, ParamType2);
  23551. FunctionCaller2 (FunctionType& function_, ParamType1& param1_, ParamType2& param2_)
  23552. : function (function_), param1 (param1_), param2 (param2_) {}
  23553. void modalStateFinished (int returnValue) { function (returnValue, param1, param2); }
  23554. private:
  23555. const FunctionType function;
  23556. ParamType1 param1;
  23557. ParamType2 param2;
  23558. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FunctionCaller2);
  23559. };
  23560. template <typename ComponentType>
  23561. class ComponentCaller1 : public ModalComponentManager::Callback
  23562. {
  23563. public:
  23564. typedef void (*FunctionType) (int, ComponentType*);
  23565. ComponentCaller1 (FunctionType& function_, ComponentType* comp_)
  23566. : function (function_), comp (comp_) {}
  23567. void modalStateFinished (int returnValue)
  23568. {
  23569. function (returnValue, static_cast <ComponentType*> (comp.get()));
  23570. }
  23571. private:
  23572. const FunctionType function;
  23573. WeakReference<Component> comp;
  23574. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentCaller1);
  23575. };
  23576. template <typename ComponentType, typename ParamType1>
  23577. class ComponentCaller2 : public ModalComponentManager::Callback
  23578. {
  23579. public:
  23580. typedef void (*FunctionType) (int, ComponentType*, ParamType1);
  23581. ComponentCaller2 (FunctionType& function_, ComponentType* comp_, ParamType1 param1_)
  23582. : function (function_), comp (comp_), param1 (param1_) {}
  23583. void modalStateFinished (int returnValue)
  23584. {
  23585. function (returnValue, static_cast <ComponentType*> (comp.get()), param1);
  23586. }
  23587. private:
  23588. const FunctionType function;
  23589. WeakReference<Component> comp;
  23590. ParamType1 param1;
  23591. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentCaller2);
  23592. };
  23593. ModalCallbackFunction();
  23594. ~ModalCallbackFunction();
  23595. JUCE_DECLARE_NON_COPYABLE (ModalCallbackFunction);
  23596. };
  23597. #endif // __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  23598. /*** End of inlined file: juce_ModalComponentManager.h ***/
  23599. class LookAndFeel;
  23600. class MouseInputSource;
  23601. class MouseInputSourceInternal;
  23602. class ComponentPeer;
  23603. class MarkerList;
  23604. class RelativeRectangle;
  23605. /**
  23606. The base class for all JUCE user-interface objects.
  23607. */
  23608. class JUCE_API Component : public MouseListener
  23609. {
  23610. public:
  23611. /** Creates a component.
  23612. To get it to actually appear, you'll also need to:
  23613. - Either add it to a parent component or use the addToDesktop() method to
  23614. make it a desktop window
  23615. - Set its size and position to something sensible
  23616. - Use setVisible() to make it visible
  23617. And for it to serve any useful purpose, you'll need to write a
  23618. subclass of Component or use one of the other types of component from
  23619. the library.
  23620. */
  23621. Component();
  23622. /** Destructor.
  23623. Note that when a component is deleted, any child components it contains are NOT
  23624. automatically deleted. It's your responsibilty to manage their lifespan - you
  23625. may want to use helper methods like deleteAllChildren(), or less haphazard
  23626. approaches like using ScopedPointers or normal object aggregation to manage them.
  23627. If the component being deleted is currently the child of another one, then during
  23628. deletion, it will be removed from its parent, and the parent will receive a childrenChanged()
  23629. callback. Any ComponentListener objects that have registered with it will also have their
  23630. ComponentListener::componentBeingDeleted() methods called.
  23631. */
  23632. virtual ~Component();
  23633. /** Creates a component, setting its name at the same time.
  23634. @see getName, setName
  23635. */
  23636. explicit Component (const String& componentName);
  23637. /** Returns the name of this component.
  23638. @see setName
  23639. */
  23640. const String& getName() const noexcept { return componentName; }
  23641. /** Sets the name of this component.
  23642. When the name changes, all registered ComponentListeners will receive a
  23643. ComponentListener::componentNameChanged() callback.
  23644. @see getName
  23645. */
  23646. virtual void setName (const String& newName);
  23647. /** Returns the ID string that was set by setComponentID().
  23648. @see setComponentID
  23649. */
  23650. const String& getComponentID() const noexcept { return componentID; }
  23651. /** Sets the component's ID string.
  23652. You can retrieve the ID using getComponentID().
  23653. @see getComponentID
  23654. */
  23655. void setComponentID (const String& newID);
  23656. /** Makes the component visible or invisible.
  23657. This method will show or hide the component.
  23658. Note that components default to being non-visible when first created.
  23659. Also note that visible components won't be seen unless all their parent components
  23660. are also visible.
  23661. This method will call visibilityChanged() and also componentVisibilityChanged()
  23662. for any component listeners that are interested in this component.
  23663. @param shouldBeVisible whether to show or hide the component
  23664. @see isVisible, isShowing, visibilityChanged, ComponentListener::componentVisibilityChanged
  23665. */
  23666. virtual void setVisible (bool shouldBeVisible);
  23667. /** Tests whether the component is visible or not.
  23668. this doesn't necessarily tell you whether this comp is actually on the screen
  23669. because this depends on whether all the parent components are also visible - use
  23670. isShowing() to find this out.
  23671. @see isShowing, setVisible
  23672. */
  23673. bool isVisible() const noexcept { return flags.visibleFlag; }
  23674. /** Called when this component's visiblility changes.
  23675. @see setVisible, isVisible
  23676. */
  23677. virtual void visibilityChanged();
  23678. /** Tests whether this component and all its parents are visible.
  23679. @returns true only if this component and all its parents are visible.
  23680. @see isVisible
  23681. */
  23682. bool isShowing() const;
  23683. /** Makes this component appear as a window on the desktop.
  23684. Note that before calling this, you should make sure that the component's opacity is
  23685. set correctly using setOpaque(). If the component is non-opaque, the windowing
  23686. system will try to create a special transparent window for it, which will generally take
  23687. a lot more CPU to operate (and might not even be possible on some platforms).
  23688. If the component is inside a parent component at the time this method is called, it
  23689. will be first be removed from that parent. Likewise if a component on the desktop
  23690. is subsequently added to another component, it'll be removed from the desktop.
  23691. @param windowStyleFlags a combination of the flags specified in the
  23692. ComponentPeer::StyleFlags enum, which define the
  23693. window's characteristics.
  23694. @param nativeWindowToAttachTo this allows an OS object to be passed-in as the window
  23695. in which the juce component should place itself. On Windows,
  23696. this would be a HWND, a HIViewRef on the Mac. Not necessarily
  23697. supported on all platforms, and best left as 0 unless you know
  23698. what you're doing
  23699. @see removeFromDesktop, isOnDesktop, userTriedToCloseWindow,
  23700. getPeer, ComponentPeer::setMinimised, ComponentPeer::StyleFlags,
  23701. ComponentPeer::getStyleFlags, ComponentPeer::setFullScreen
  23702. */
  23703. virtual void addToDesktop (int windowStyleFlags,
  23704. void* nativeWindowToAttachTo = nullptr);
  23705. /** If the component is currently showing on the desktop, this will hide it.
  23706. You can also use setVisible() to hide a desktop window temporarily, but
  23707. removeFromDesktop() will free any system resources that are being used up.
  23708. @see addToDesktop, isOnDesktop
  23709. */
  23710. void removeFromDesktop();
  23711. /** Returns true if this component is currently showing on the desktop.
  23712. @see addToDesktop, removeFromDesktop
  23713. */
  23714. bool isOnDesktop() const noexcept;
  23715. /** Returns the heavyweight window that contains this component.
  23716. If this component is itself on the desktop, this will return the window
  23717. object that it is using. Otherwise, it will return the window of
  23718. its top-level parent component.
  23719. This may return 0 if there isn't a desktop component.
  23720. @see addToDesktop, isOnDesktop
  23721. */
  23722. ComponentPeer* getPeer() const;
  23723. /** For components on the desktop, this is called if the system wants to close the window.
  23724. This is a signal that either the user or the system wants the window to close. The
  23725. default implementation of this method will trigger an assertion to warn you that your
  23726. component should do something about it, but you can override this to ignore the event
  23727. if you want.
  23728. */
  23729. virtual void userTriedToCloseWindow();
  23730. /** Called for a desktop component which has just been minimised or un-minimised.
  23731. This will only be called for components on the desktop.
  23732. @see getPeer, ComponentPeer::setMinimised, ComponentPeer::isMinimised
  23733. */
  23734. virtual void minimisationStateChanged (bool isNowMinimised);
  23735. /** Brings the component to the front of its siblings.
  23736. If some of the component's siblings have had their 'always-on-top' flag set,
  23737. then they will still be kept in front of this one (unless of course this
  23738. one is also 'always-on-top').
  23739. @param shouldAlsoGainFocus if true, this will also try to assign keyboard focus
  23740. to the component (see grabKeyboardFocus() for more details)
  23741. @see toBack, toBehind, setAlwaysOnTop
  23742. */
  23743. void toFront (bool shouldAlsoGainFocus);
  23744. /** Changes this component's z-order to be at the back of all its siblings.
  23745. If the component is set to be 'always-on-top', it will only be moved to the
  23746. back of the other other 'always-on-top' components.
  23747. @see toFront, toBehind, setAlwaysOnTop
  23748. */
  23749. void toBack();
  23750. /** Changes this component's z-order so that it's just behind another component.
  23751. @see toFront, toBack
  23752. */
  23753. void toBehind (Component* other);
  23754. /** Sets whether the component should always be kept at the front of its siblings.
  23755. @see isAlwaysOnTop
  23756. */
  23757. void setAlwaysOnTop (bool shouldStayOnTop);
  23758. /** Returns true if this component is set to always stay in front of its siblings.
  23759. @see setAlwaysOnTop
  23760. */
  23761. bool isAlwaysOnTop() const noexcept;
  23762. /** Returns the x coordinate of the component's left edge.
  23763. This is a distance in pixels from the left edge of the component's parent.
  23764. Note that if you've used setTransform() to apply a transform, then the component's
  23765. bounds will no longer be a direct reflection of the position at which it appears within
  23766. its parent, as the transform will be applied to its bounding box.
  23767. */
  23768. inline int getX() const noexcept { return bounds.getX(); }
  23769. /** Returns the y coordinate of the top of this component.
  23770. This is a distance in pixels from the top edge of the component's parent.
  23771. Note that if you've used setTransform() to apply a transform, then the component's
  23772. bounds will no longer be a direct reflection of the position at which it appears within
  23773. its parent, as the transform will be applied to its bounding box.
  23774. */
  23775. inline int getY() const noexcept { return bounds.getY(); }
  23776. /** Returns the component's width in pixels. */
  23777. inline int getWidth() const noexcept { return bounds.getWidth(); }
  23778. /** Returns the component's height in pixels. */
  23779. inline int getHeight() const noexcept { return bounds.getHeight(); }
  23780. /** Returns the x coordinate of the component's right-hand edge.
  23781. This is a distance in pixels from the left edge of the component's parent.
  23782. Note that if you've used setTransform() to apply a transform, then the component's
  23783. bounds will no longer be a direct reflection of the position at which it appears within
  23784. its parent, as the transform will be applied to its bounding box.
  23785. */
  23786. int getRight() const noexcept { return bounds.getRight(); }
  23787. /** Returns the component's top-left position as a Point. */
  23788. Point<int> getPosition() const noexcept { return bounds.getPosition(); }
  23789. /** Returns the y coordinate of the bottom edge of this component.
  23790. This is a distance in pixels from the top edge of the component's parent.
  23791. Note that if you've used setTransform() to apply a transform, then the component's
  23792. bounds will no longer be a direct reflection of the position at which it appears within
  23793. its parent, as the transform will be applied to its bounding box.
  23794. */
  23795. int getBottom() const noexcept { return bounds.getBottom(); }
  23796. /** Returns this component's bounding box.
  23797. The rectangle returned is relative to the top-left of the component's parent.
  23798. Note that if you've used setTransform() to apply a transform, then the component's
  23799. bounds will no longer be a direct reflection of the position at which it appears within
  23800. its parent, as the transform will be applied to its bounding box.
  23801. */
  23802. const Rectangle<int>& getBounds() const noexcept { return bounds; }
  23803. /** Returns the component's bounds, relative to its own origin.
  23804. This is like getBounds(), but returns the rectangle in local coordinates, In practice, it'll
  23805. return a rectangle with position (0, 0), and the same size as this component.
  23806. */
  23807. Rectangle<int> getLocalBounds() const noexcept;
  23808. /** Returns the area of this component's parent which this component covers.
  23809. The returned area is relative to the parent's coordinate space.
  23810. If the component has an affine transform specified, then the resulting area will be
  23811. the smallest rectangle that fully covers the component's transformed bounding box.
  23812. If this component has no parent, the return value will simply be the same as getBounds().
  23813. */
  23814. Rectangle<int> getBoundsInParent() const noexcept;
  23815. /** Returns the region of this component that's not obscured by other, opaque components.
  23816. The RectangleList that is returned represents the area of this component
  23817. which isn't covered by opaque child components.
  23818. If includeSiblings is true, it will also take into account any siblings
  23819. that may be overlapping the component.
  23820. */
  23821. void getVisibleArea (RectangleList& result,
  23822. bool includeSiblings) const;
  23823. /** Returns this component's x coordinate relative the the screen's top-left origin.
  23824. @see getX, localPointToGlobal
  23825. */
  23826. int getScreenX() const;
  23827. /** Returns this component's y coordinate relative the the screen's top-left origin.
  23828. @see getY, localPointToGlobal
  23829. */
  23830. int getScreenY() const;
  23831. /** Returns the position of this component's top-left corner relative to the screen's top-left.
  23832. @see getScreenBounds
  23833. */
  23834. Point<int> getScreenPosition() const;
  23835. /** Returns the bounds of this component, relative to the screen's top-left.
  23836. @see getScreenPosition
  23837. */
  23838. Rectangle<int> getScreenBounds() const;
  23839. /** Converts a point to be relative to this component's coordinate space.
  23840. This takes a point relative to a different component, and returns its position relative to this
  23841. component. If the sourceComponent parameter is null, the source point is assumed to be a global
  23842. screen coordinate.
  23843. */
  23844. Point<int> getLocalPoint (const Component* sourceComponent,
  23845. const Point<int>& pointRelativeToSourceComponent) const;
  23846. /** Converts a rectangle to be relative to this component's coordinate space.
  23847. This takes a rectangle that is relative to a different component, and returns its position relative
  23848. to this component. If the sourceComponent parameter is null, the source rectangle is assumed to be
  23849. a screen coordinate.
  23850. If you've used setTransform() to apply one or more transforms to components, then the source rectangle
  23851. may not actually be rectanglular when converted to the target space, so in that situation this will return
  23852. the smallest rectangle that fully contains the transformed area.
  23853. */
  23854. Rectangle<int> getLocalArea (const Component* sourceComponent,
  23855. const Rectangle<int>& areaRelativeToSourceComponent) const;
  23856. /** Converts a point relative to this component's top-left into a screen coordinate.
  23857. @see getLocalPoint, localAreaToGlobal
  23858. */
  23859. Point<int> localPointToGlobal (const Point<int>& localPoint) const;
  23860. /** Converts a rectangle from this component's coordinate space to a screen coordinate.
  23861. If you've used setTransform() to apply one or more transforms to components, then the source rectangle
  23862. may not actually be rectanglular when converted to the target space, so in that situation this will return
  23863. the smallest rectangle that fully contains the transformed area.
  23864. @see getLocalPoint, localPointToGlobal
  23865. */
  23866. Rectangle<int> localAreaToGlobal (const Rectangle<int>& localArea) const;
  23867. /** Moves the component to a new position.
  23868. Changes the component's top-left position (without changing its size).
  23869. The position is relative to the top-left of the component's parent.
  23870. If the component actually moves, this method will make a synchronous call to moved().
  23871. Note that if you've used setTransform() to apply a transform, then the component's
  23872. bounds will no longer be a direct reflection of the position at which it appears within
  23873. its parent, as the transform will be applied to whatever bounds you set for it.
  23874. @see setBounds, ComponentListener::componentMovedOrResized
  23875. */
  23876. void setTopLeftPosition (int x, int y);
  23877. /** Moves the component to a new position.
  23878. Changes the position of the component's top-right corner (keeping it the same size).
  23879. The position is relative to the top-left of the component's parent.
  23880. If the component actually moves, this method will make a synchronous call to moved().
  23881. Note that if you've used setTransform() to apply a transform, then the component's
  23882. bounds will no longer be a direct reflection of the position at which it appears within
  23883. its parent, as the transform will be applied to whatever bounds you set for it.
  23884. */
  23885. void setTopRightPosition (int x, int y);
  23886. /** Changes the size of the component.
  23887. A synchronous call to resized() will be occur if the size actually changes.
  23888. Note that if you've used setTransform() to apply a transform, then the component's
  23889. bounds will no longer be a direct reflection of the position at which it appears within
  23890. its parent, as the transform will be applied to whatever bounds you set for it.
  23891. */
  23892. void setSize (int newWidth, int newHeight);
  23893. /** Changes the component's position and size.
  23894. The coordinates are relative to the top-left of the component's parent, or relative
  23895. to the origin of the screen is the component is on the desktop.
  23896. If this method changes the component's top-left position, it will make a synchronous
  23897. call to moved(). If it changes the size, it will also make a call to resized().
  23898. Note that if you've used setTransform() to apply a transform, then the component's
  23899. bounds will no longer be a direct reflection of the position at which it appears within
  23900. its parent, as the transform will be applied to whatever bounds you set for it.
  23901. @see setTopLeftPosition, setSize, ComponentListener::componentMovedOrResized
  23902. */
  23903. void setBounds (int x, int y, int width, int height);
  23904. /** Changes the component's position and size.
  23905. The coordinates are relative to the top-left of the component's parent, or relative
  23906. to the origin of the screen is the component is on the desktop.
  23907. If this method changes the component's top-left position, it will make a synchronous
  23908. call to moved(). If it changes the size, it will also make a call to resized().
  23909. Note that if you've used setTransform() to apply a transform, then the component's
  23910. bounds will no longer be a direct reflection of the position at which it appears within
  23911. its parent, as the transform will be applied to whatever bounds you set for it.
  23912. @see setBounds
  23913. */
  23914. void setBounds (const Rectangle<int>& newBounds);
  23915. /** Changes the component's position and size.
  23916. This is similar to the other setBounds() methods, but uses RelativeRectangle::applyToComponent()
  23917. to set the position, This uses a Component::Positioner to make sure that any dynamic
  23918. expressions are used in the RelativeRectangle will be automatically re-applied to the
  23919. component's bounds when the source values change. See RelativeRectangle::applyToComponent()
  23920. for more details.
  23921. When using relative expressions, the following symbols are available:
  23922. - "left", "right", "top", "bottom" refer to the position of those edges in this component, so
  23923. e.g. for a component whose width is always 100, you might set the right edge to the "left + 100".
  23924. - "[id].left", "[id].right", "[id].top", "[id].bottom", "[id].width", "[id].height", where [id] is
  23925. the identifier of one of this component's siblings. A component's identifier is set with
  23926. Component::setComponentID(). So for example if you want your component to always be 50 pixels to the
  23927. right of the one called "xyz", you could set your left edge to be "xyz.right + 50".
  23928. - Instead of an [id], you can use the name "parent" to refer to this component's parent. Like
  23929. any other component, these values are relative to their component's parent, so "parent.right" won't be
  23930. very useful for positioning a component because it refers to a position with the parent's parent.. but
  23931. "parent.width" can be used for setting positions relative to the parent's size. E.g. to make a 10x10
  23932. component which remains 1 pixel away from its parent's bottom-right, you could use
  23933. "right - 10, bottom - 10, parent.width - 1, parent.height - 1".
  23934. - The name of one of the parent component's markers can also be used as a symbol. For markers to be
  23935. used, the parent component must implement its Component::getMarkers() method, and return at least one
  23936. valid MarkerList. So if you want your component's top edge to be 10 pixels below the
  23937. marker called "foobar", you'd set it to "foobar + 10".
  23938. See the Expression class for details about the operators that are supported, but for example
  23939. if you wanted to make your component remain centred within its parent with a size of 100, 100,
  23940. you could express it as:
  23941. @code myComp.setBounds (RelativeBounds ("parent.width / 2 - 50, parent.height / 2 - 50, left + 100, top + 100"));
  23942. @endcode
  23943. ..or an alternative way to achieve the same thing:
  23944. @code myComp.setBounds (RelativeBounds ("right - 100, bottom - 100, parent.width / 2 + 50, parent.height / 2 + 50"));
  23945. @endcode
  23946. Or if you wanted a 100x100 component whose top edge is lined up to a marker called "topMarker" and
  23947. which is positioned 50 pixels to the right of another component called "otherComp", you could write:
  23948. @code myComp.setBounds (RelativeBounds ("otherComp.right + 50, topMarker, left + 100, top + 100"));
  23949. @endcode
  23950. Be careful not to make your coordinate expressions recursive, though, or exceptions and assertions will
  23951. be thrown!
  23952. @see setBounds, RelativeRectangle::applyToComponent(), Expression
  23953. */
  23954. void setBounds (const RelativeRectangle& newBounds);
  23955. /** Sets the component's bounds with an expression.
  23956. The string is parsed as a RelativeRectangle expression - see the notes for
  23957. Component::setBounds (const RelativeRectangle&) for more information. This method is
  23958. basically just a shortcut for writing setBounds (RelativeRectangle ("..."))
  23959. */
  23960. void setBounds (const String& newBoundsExpression);
  23961. /** Changes the component's position and size in terms of fractions of its parent's size.
  23962. The values are factors of the parent's size, so for example
  23963. setBoundsRelative (0.2f, 0.2f, 0.5f, 0.5f) would give it half the
  23964. width and height of the parent, with its top-left position 20% of
  23965. the way across and down the parent.
  23966. @see setBounds
  23967. */
  23968. void setBoundsRelative (float proportionalX, float proportionalY,
  23969. float proportionalWidth, float proportionalHeight);
  23970. /** Changes the component's position and size based on the amount of space to leave around it.
  23971. This will position the component within its parent, leaving the specified number of
  23972. pixels around each edge.
  23973. @see setBounds
  23974. */
  23975. void setBoundsInset (const BorderSize<int>& borders);
  23976. /** Positions the component within a given rectangle, keeping its proportions
  23977. unchanged.
  23978. If onlyReduceInSize is false, the component will be resized to fill as much of the
  23979. rectangle as possible without changing its aspect ratio (the component's
  23980. current size is used to determine its aspect ratio, so a zero-size component
  23981. won't work here). If onlyReduceInSize is true, it will only be resized if it's
  23982. too big to fit inside the rectangle.
  23983. It will then be positioned within the rectangle according to the justification flags
  23984. specified.
  23985. @see setBounds
  23986. */
  23987. void setBoundsToFit (int x, int y, int width, int height,
  23988. const Justification& justification,
  23989. bool onlyReduceInSize);
  23990. /** Changes the position of the component's centre.
  23991. Leaves the component's size unchanged, but sets the position of its centre
  23992. relative to its parent's top-left.
  23993. @see setBounds
  23994. */
  23995. void setCentrePosition (int x, int y);
  23996. /** Changes the position of the component's centre.
  23997. Leaves the position unchanged, but positions its centre relative to its
  23998. parent's size. E.g. setCentreRelative (0.5f, 0.5f) would place it centrally in
  23999. its parent.
  24000. */
  24001. void setCentreRelative (float x, float y);
  24002. /** Changes the component's size and centres it within its parent.
  24003. After changing the size, the component will be moved so that it's
  24004. centred within its parent. If the component is on the desktop (or has no
  24005. parent component), then it'll be centred within the main monitor area.
  24006. */
  24007. void centreWithSize (int width, int height);
  24008. /** Sets a transform matrix to be applied to this component.
  24009. If you set a transform for a component, the component's position will be warped by it, relative to
  24010. the component's parent's top-left origin. This means that the values you pass into setBounds() will no
  24011. longer reflect the actual area within the parent that the component covers, as the bounds will be
  24012. transformed and the component will probably end up actually appearing somewhere else within its parent.
  24013. When using transforms you need to be extremely careful when converting coordinates between the
  24014. coordinate spaces of different components or the screen - you should always use getLocalPoint(),
  24015. getLocalArea(), etc to do this, and never just manually add a component's position to a point in order to
  24016. convert it between different components (but I'm sure you would never have done that anyway...).
  24017. Currently, transforms are not supported for desktop windows, so the transform will be ignored if you
  24018. put a component on the desktop.
  24019. To remove a component's transform, simply pass AffineTransform::identity as the parameter to this method.
  24020. */
  24021. void setTransform (const AffineTransform& transform);
  24022. /** Returns the transform that is currently being applied to this component.
  24023. For more details about transforms, see setTransform().
  24024. @see setTransform
  24025. */
  24026. AffineTransform getTransform() const;
  24027. /** Returns true if a non-identity transform is being applied to this component.
  24028. For more details about transforms, see setTransform().
  24029. @see setTransform
  24030. */
  24031. bool isTransformed() const noexcept;
  24032. /** Returns a proportion of the component's width.
  24033. This is a handy equivalent of (getWidth() * proportion).
  24034. */
  24035. int proportionOfWidth (float proportion) const noexcept;
  24036. /** Returns a proportion of the component's height.
  24037. This is a handy equivalent of (getHeight() * proportion).
  24038. */
  24039. int proportionOfHeight (float proportion) const noexcept;
  24040. /** Returns the width of the component's parent.
  24041. If the component has no parent (i.e. if it's on the desktop), this will return
  24042. the width of the screen.
  24043. */
  24044. int getParentWidth() const noexcept;
  24045. /** Returns the height of the component's parent.
  24046. If the component has no parent (i.e. if it's on the desktop), this will return
  24047. the height of the screen.
  24048. */
  24049. int getParentHeight() const noexcept;
  24050. /** Returns the screen coordinates of the monitor that contains this component.
  24051. If there's only one monitor, this will return its size - if there are multiple
  24052. monitors, it will return the area of the monitor that contains the component's
  24053. centre.
  24054. */
  24055. Rectangle<int> getParentMonitorArea() const;
  24056. /** Returns the number of child components that this component contains.
  24057. @see getChildComponent, getIndexOfChildComponent
  24058. */
  24059. int getNumChildComponents() const noexcept;
  24060. /** Returns one of this component's child components, by it index.
  24061. The component with index 0 is at the back of the z-order, the one at the
  24062. front will have index (getNumChildComponents() - 1).
  24063. If the index is out-of-range, this will return a null pointer.
  24064. @see getNumChildComponents, getIndexOfChildComponent
  24065. */
  24066. Component* getChildComponent (int index) const noexcept;
  24067. /** Returns the index of this component in the list of child components.
  24068. A value of 0 means it is first in the list (i.e. behind all other components). Higher
  24069. values are further towards the front.
  24070. Returns -1 if the component passed-in is not a child of this component.
  24071. @see getNumChildComponents, getChildComponent, addChildComponent, toFront, toBack, toBehind
  24072. */
  24073. int getIndexOfChildComponent (const Component* child) const noexcept;
  24074. /** Adds a child component to this one.
  24075. Adding a child component does not mean that the component will own or delete the child - it's
  24076. your responsibility to delete the component. Note that it's safe to delete a component
  24077. without first removing it from its parent - doing so will automatically remove it and
  24078. send out the appropriate notifications before the deletion completes.
  24079. If the child is already a child of this component, then no action will be taken, and its
  24080. z-order will be left unchanged.
  24081. @param child the new component to add. If the component passed-in is already
  24082. the child of another component, it'll first be removed from it current parent.
  24083. @param zOrder The index in the child-list at which this component should be inserted.
  24084. A value of -1 will insert it in front of the others, 0 is the back.
  24085. @see removeChildComponent, addAndMakeVisible, getChild, ComponentListener::componentChildrenChanged
  24086. */
  24087. void addChildComponent (Component* child, int zOrder = -1);
  24088. /** Adds a child component to this one, and also makes the child visible if it isn't.
  24089. Quite a useful function, this is just the same as calling setVisible (true) on the child
  24090. and then addChildComponent(). See addChildComponent() for more details.
  24091. */
  24092. void addAndMakeVisible (Component* child, int zOrder = -1);
  24093. /** Removes one of this component's child-components.
  24094. If the child passed-in isn't actually a child of this component (either because
  24095. it's invalid or is the child of a different parent), then no action is taken.
  24096. Note that removing a child will not delete it! But it's ok to delete a component
  24097. without first removing it - doing so will automatically remove it and send out the
  24098. appropriate notifications before the deletion completes.
  24099. @see addChildComponent, ComponentListener::componentChildrenChanged
  24100. */
  24101. void removeChildComponent (Component* childToRemove);
  24102. /** Removes one of this component's child-components by index.
  24103. This will return a pointer to the component that was removed, or null if
  24104. the index was out-of-range.
  24105. Note that removing a child will not delete it! But it's ok to delete a component
  24106. without first removing it - doing so will automatically remove it and send out the
  24107. appropriate notifications before the deletion completes.
  24108. @see addChildComponent, ComponentListener::componentChildrenChanged
  24109. */
  24110. Component* removeChildComponent (int childIndexToRemove);
  24111. /** Removes all this component's children.
  24112. Note that this won't delete them! To do that, use deleteAllChildren() instead.
  24113. */
  24114. void removeAllChildren();
  24115. /** Removes all this component's children, and deletes them.
  24116. @see removeAllChildren
  24117. */
  24118. void deleteAllChildren();
  24119. /** Returns the component which this component is inside.
  24120. If this is the highest-level component or hasn't yet been added to
  24121. a parent, this will return null.
  24122. */
  24123. Component* getParentComponent() const noexcept { return parentComponent; }
  24124. /** Searches the parent components for a component of a specified class.
  24125. For example findParentComponentOfClass \<MyComp\>() would return the first parent
  24126. component that can be dynamically cast to a MyComp, or will return 0 if none
  24127. of the parents are suitable.
  24128. N.B. The dummy parameter is needed to work around a VC6 compiler bug.
  24129. */
  24130. template <class TargetClass>
  24131. TargetClass* findParentComponentOfClass (TargetClass* const dummyParameter = nullptr) const
  24132. {
  24133. (void) dummyParameter;
  24134. Component* p = parentComponent;
  24135. while (p != nullptr)
  24136. {
  24137. TargetClass* target = dynamic_cast <TargetClass*> (p);
  24138. if (target != nullptr)
  24139. return target;
  24140. p = p->parentComponent;
  24141. }
  24142. return nullptr;
  24143. }
  24144. /** Returns the highest-level component which contains this one or its parents.
  24145. This will search upwards in the parent-hierarchy from this component, until it
  24146. finds the highest one that doesn't have a parent (i.e. is on the desktop or
  24147. not yet added to a parent), and will return that.
  24148. */
  24149. Component* getTopLevelComponent() const noexcept;
  24150. /** Checks whether a component is anywhere inside this component or its children.
  24151. This will recursively check through this component's children to see if the
  24152. given component is anywhere inside.
  24153. */
  24154. bool isParentOf (const Component* possibleChild) const noexcept;
  24155. /** Called to indicate that the component's parents have changed.
  24156. When a component is added or removed from its parent, this method will
  24157. be called on all of its children (recursively - so all children of its
  24158. children will also be called as well).
  24159. Subclasses can override this if they need to react to this in some way.
  24160. @see getParentComponent, isShowing, ComponentListener::componentParentHierarchyChanged
  24161. */
  24162. virtual void parentHierarchyChanged();
  24163. /** Subclasses can use this callback to be told when children are added or removed.
  24164. @see parentHierarchyChanged
  24165. */
  24166. virtual void childrenChanged();
  24167. /** Tests whether a given point inside the component.
  24168. Overriding this method allows you to create components which only intercept
  24169. mouse-clicks within a user-defined area.
  24170. This is called to find out whether a particular x, y coordinate is
  24171. considered to be inside the component or not, and is used by methods such
  24172. as contains() and getComponentAt() to work out which component
  24173. the mouse is clicked on.
  24174. Components with custom shapes will probably want to override it to perform
  24175. some more complex hit-testing.
  24176. The default implementation of this method returns either true or false,
  24177. depending on the value that was set by calling setInterceptsMouseClicks() (true
  24178. is the default return value).
  24179. Note that the hit-test region is not related to the opacity with which
  24180. areas of a component are painted.
  24181. Applications should never call hitTest() directly - instead use the
  24182. contains() method, because this will also test for occlusion by the
  24183. component's parent.
  24184. Note that for components on the desktop, this method will be ignored, because it's
  24185. not always possible to implement this behaviour on all platforms.
  24186. @param x the x coordinate to test, relative to the left hand edge of this
  24187. component. This value is guaranteed to be greater than or equal to
  24188. zero, and less than the component's width
  24189. @param y the y coordinate to test, relative to the top edge of this
  24190. component. This value is guaranteed to be greater than or equal to
  24191. zero, and less than the component's height
  24192. @returns true if the click is considered to be inside the component
  24193. @see setInterceptsMouseClicks, contains
  24194. */
  24195. virtual bool hitTest (int x, int y);
  24196. /** Changes the default return value for the hitTest() method.
  24197. Setting this to false is an easy way to make a component pass its mouse-clicks
  24198. through to the components behind it.
  24199. When a component is created, the default setting for this is true.
  24200. @param allowClicksOnThisComponent if true, hitTest() will always return true; if false, it will
  24201. return false (or true for child components if allowClicksOnChildComponents
  24202. is true)
  24203. @param allowClicksOnChildComponents if this is true and allowClicksOnThisComponent is false, then child
  24204. components can be clicked on as normal but clicks on this component pass
  24205. straight through; if this is false and allowClicksOnThisComponent
  24206. is false, then neither this component nor any child components can
  24207. be clicked on
  24208. @see hitTest, getInterceptsMouseClicks
  24209. */
  24210. void setInterceptsMouseClicks (bool allowClicksOnThisComponent,
  24211. bool allowClicksOnChildComponents) noexcept;
  24212. /** Retrieves the current state of the mouse-click interception flags.
  24213. On return, the two parameters are set to the state used in the last call to
  24214. setInterceptsMouseClicks().
  24215. @see setInterceptsMouseClicks
  24216. */
  24217. void getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  24218. bool& allowsClicksOnChildComponents) const noexcept;
  24219. /** Returns true if a given point lies within this component or one of its children.
  24220. Never override this method! Use hitTest to create custom hit regions.
  24221. @param localPoint the coordinate to test, relative to this component's top-left.
  24222. @returns true if the point is within the component's hit-test area, but only if
  24223. that part of the component isn't clipped by its parent component. Note
  24224. that this won't take into account any overlapping sibling components
  24225. which might be in the way - for that, see reallyContains()
  24226. @see hitTest, reallyContains, getComponentAt
  24227. */
  24228. bool contains (const Point<int>& localPoint);
  24229. /** Returns true if a given point lies in this component, taking any overlapping
  24230. siblings into account.
  24231. @param localPoint the coordinate to test, relative to this component's top-left.
  24232. @param returnTrueIfWithinAChild if the point actually lies within a child of this component,
  24233. this determines whether that is counted as a hit.
  24234. @see contains, getComponentAt
  24235. */
  24236. bool reallyContains (const Point<int>& localPoint, bool returnTrueIfWithinAChild);
  24237. /** Returns the component at a certain point within this one.
  24238. @param x the x coordinate to test, relative to this component's left edge.
  24239. @param y the y coordinate to test, relative to this component's top edge.
  24240. @returns the component that is at this position - which may be 0, this component,
  24241. or one of its children. Note that overlapping siblings that might actually
  24242. be in the way are not taken into account by this method - to account for these,
  24243. instead call getComponentAt on the top-level parent of this component.
  24244. @see hitTest, contains, reallyContains
  24245. */
  24246. Component* getComponentAt (int x, int y);
  24247. /** Returns the component at a certain point within this one.
  24248. @param position the coordinate to test, relative to this component's top-left.
  24249. @returns the component that is at this position - which may be 0, this component,
  24250. or one of its children. Note that overlapping siblings that might actually
  24251. be in the way are not taken into account by this method - to account for these,
  24252. instead call getComponentAt on the top-level parent of this component.
  24253. @see hitTest, contains, reallyContains
  24254. */
  24255. Component* getComponentAt (const Point<int>& position);
  24256. /** Marks the whole component as needing to be redrawn.
  24257. Calling this will not do any repainting immediately, but will mark the component
  24258. as 'dirty'. At some point in the near future the operating system will send a paint
  24259. message, which will redraw all the dirty regions of all components.
  24260. There's no guarantee about how soon after calling repaint() the redraw will actually
  24261. happen, and other queued events may be delivered before a redraw is done.
  24262. If the setBufferedToImage() method has been used to cause this component
  24263. to use a buffer, the repaint() call will invalidate the component's buffer.
  24264. To redraw just a subsection of the component rather than the whole thing,
  24265. use the repaint (int, int, int, int) method.
  24266. @see paint
  24267. */
  24268. void repaint();
  24269. /** Marks a subsection of this component as needing to be redrawn.
  24270. Calling this will not do any repainting immediately, but will mark the given region
  24271. of the component as 'dirty'. At some point in the near future the operating system
  24272. will send a paint message, which will redraw all the dirty regions of all components.
  24273. There's no guarantee about how soon after calling repaint() the redraw will actually
  24274. happen, and other queued events may be delivered before a redraw is done.
  24275. The region that is passed in will be clipped to keep it within the bounds of this
  24276. component.
  24277. @see repaint()
  24278. */
  24279. void repaint (int x, int y, int width, int height);
  24280. /** Marks a subsection of this component as needing to be redrawn.
  24281. Calling this will not do any repainting immediately, but will mark the given region
  24282. of the component as 'dirty'. At some point in the near future the operating system
  24283. will send a paint message, which will redraw all the dirty regions of all components.
  24284. There's no guarantee about how soon after calling repaint() the redraw will actually
  24285. happen, and other queued events may be delivered before a redraw is done.
  24286. The region that is passed in will be clipped to keep it within the bounds of this
  24287. component.
  24288. @see repaint()
  24289. */
  24290. void repaint (const Rectangle<int>& area);
  24291. /** Makes the component use an internal buffer to optimise its redrawing.
  24292. Setting this flag to true will cause the component to allocate an
  24293. internal buffer into which it paints itself, so that when asked to
  24294. redraw itself, it can use this buffer rather than actually calling the
  24295. paint() method.
  24296. The buffer is kept until the repaint() method is called directly on
  24297. this component (or until it is resized), when the image is invalidated
  24298. and then redrawn the next time the component is painted.
  24299. Note that only the drawing that happens within the component's paint()
  24300. method is drawn into the buffer, it's child components are not buffered, and
  24301. nor is the paintOverChildren() method.
  24302. @see repaint, paint, createComponentSnapshot
  24303. */
  24304. void setBufferedToImage (bool shouldBeBuffered);
  24305. /** Generates a snapshot of part of this component.
  24306. This will return a new Image, the size of the rectangle specified,
  24307. containing a snapshot of the specified area of the component and all
  24308. its children.
  24309. The image may or may not have an alpha-channel, depending on whether the
  24310. image is opaque or not.
  24311. If the clipImageToComponentBounds parameter is true and the area is greater than
  24312. the size of the component, it'll be clipped. If clipImageToComponentBounds is false
  24313. then parts of the component beyond its bounds can be drawn.
  24314. @see paintEntireComponent
  24315. */
  24316. Image createComponentSnapshot (const Rectangle<int>& areaToGrab,
  24317. bool clipImageToComponentBounds = true);
  24318. /** Draws this component and all its subcomponents onto the specified graphics
  24319. context.
  24320. You should very rarely have to use this method, it's simply there in case you need
  24321. to draw a component with a custom graphics context for some reason, e.g. for
  24322. creating a snapshot of the component.
  24323. It calls paint(), paintOverChildren() and recursively calls paintEntireComponent()
  24324. on its children in order to render the entire tree.
  24325. The graphics context may be left in an undefined state after this method returns,
  24326. so you may need to reset it if you're going to use it again.
  24327. If ignoreAlphaLevel is false, then the component will be drawn with the opacity level
  24328. specified by getAlpha(); if ignoreAlphaLevel is true, then this will be ignored and
  24329. an alpha of 1.0 will be used.
  24330. */
  24331. void paintEntireComponent (Graphics& context, bool ignoreAlphaLevel);
  24332. /** This allows you to indicate that this component doesn't require its graphics
  24333. context to be clipped when it is being painted.
  24334. Most people will never need to use this setting, but in situations where you have a very large
  24335. number of simple components being rendered, and where they are guaranteed never to do any drawing
  24336. beyond their own boundaries, setting this to true will reduce the overhead involved in clipping
  24337. the graphics context that gets passed to the component's paint() callback.
  24338. If you enable this mode, you'll need to make sure your paint method doesn't call anything like
  24339. Graphics::fillAll(), and doesn't draw beyond the component's bounds, because that'll produce
  24340. artifacts. Your component also can't have any child components that may be placed beyond its
  24341. bounds.
  24342. */
  24343. void setPaintingIsUnclipped (bool shouldPaintWithoutClipping) noexcept;
  24344. /** Adds an effect filter to alter the component's appearance.
  24345. When a component has an effect filter set, then this is applied to the
  24346. results of its paint() method. There are a few preset effects, such as
  24347. a drop-shadow or glow, but they can be user-defined as well.
  24348. The effect that is passed in will not be deleted by the component - the
  24349. caller must take care of deleting it.
  24350. To remove an effect from a component, pass a null pointer in as the parameter.
  24351. @see ImageEffectFilter, DropShadowEffect, GlowEffect
  24352. */
  24353. void setComponentEffect (ImageEffectFilter* newEffect);
  24354. /** Returns the current component effect.
  24355. @see setComponentEffect
  24356. */
  24357. ImageEffectFilter* getComponentEffect() const noexcept { return effect; }
  24358. /** Finds the appropriate look-and-feel to use for this component.
  24359. If the component hasn't had a look-and-feel explicitly set, this will
  24360. return the parent's look-and-feel, or just the default one if there's no
  24361. parent.
  24362. @see setLookAndFeel, lookAndFeelChanged
  24363. */
  24364. LookAndFeel& getLookAndFeel() const noexcept;
  24365. /** Sets the look and feel to use for this component.
  24366. This will also change the look and feel for any child components that haven't
  24367. had their look set explicitly.
  24368. The object passed in will not be deleted by the component, so it's the caller's
  24369. responsibility to manage it. It may be used at any time until this component
  24370. has been deleted.
  24371. Calling this method will also invoke the sendLookAndFeelChange() method.
  24372. @see getLookAndFeel, lookAndFeelChanged
  24373. */
  24374. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  24375. /** Called to let the component react to a change in the look-and-feel setting.
  24376. When the look-and-feel is changed for a component, this will be called in
  24377. all its child components, recursively.
  24378. It can also be triggered manually by the sendLookAndFeelChange() method, in case
  24379. an application uses a LookAndFeel class that might have changed internally.
  24380. @see sendLookAndFeelChange, getLookAndFeel
  24381. */
  24382. virtual void lookAndFeelChanged();
  24383. /** Calls the lookAndFeelChanged() method in this component and all its children.
  24384. This will recurse through the children and their children, calling lookAndFeelChanged()
  24385. on them all.
  24386. @see lookAndFeelChanged
  24387. */
  24388. void sendLookAndFeelChange();
  24389. /** Indicates whether any parts of the component might be transparent.
  24390. Components that always paint all of their contents with solid colour and
  24391. thus completely cover any components behind them should use this method
  24392. to tell the repaint system that they are opaque.
  24393. This information is used to optimise drawing, because it means that
  24394. objects underneath opaque windows don't need to be painted.
  24395. By default, components are considered transparent, unless this is used to
  24396. make it otherwise.
  24397. @see isOpaque, getVisibleArea
  24398. */
  24399. void setOpaque (bool shouldBeOpaque);
  24400. /** Returns true if no parts of this component are transparent.
  24401. @returns the value that was set by setOpaque, (the default being false)
  24402. @see setOpaque
  24403. */
  24404. bool isOpaque() const noexcept;
  24405. /** Indicates whether the component should be brought to the front when clicked.
  24406. Setting this flag to true will cause the component to be brought to the front
  24407. when the mouse is clicked somewhere inside it or its child components.
  24408. Note that a top-level desktop window might still be brought to the front by the
  24409. operating system when it's clicked, depending on how the OS works.
  24410. By default this is set to false.
  24411. @see setMouseClickGrabsKeyboardFocus
  24412. */
  24413. void setBroughtToFrontOnMouseClick (bool shouldBeBroughtToFront) noexcept;
  24414. /** Indicates whether the component should be brought to the front when clicked-on.
  24415. @see setBroughtToFrontOnMouseClick
  24416. */
  24417. bool isBroughtToFrontOnMouseClick() const noexcept;
  24418. // Keyboard focus methods
  24419. /** Sets a flag to indicate whether this component needs keyboard focus or not.
  24420. By default components aren't actually interested in gaining the
  24421. focus, but this method can be used to turn this on.
  24422. See the grabKeyboardFocus() method for details about the way a component
  24423. is chosen to receive the focus.
  24424. @see grabKeyboardFocus, getWantsKeyboardFocus
  24425. */
  24426. void setWantsKeyboardFocus (bool wantsFocus) noexcept;
  24427. /** Returns true if the component is interested in getting keyboard focus.
  24428. This returns the flag set by setWantsKeyboardFocus(). The default
  24429. setting is false.
  24430. @see setWantsKeyboardFocus
  24431. */
  24432. bool getWantsKeyboardFocus() const noexcept;
  24433. /** Chooses whether a click on this component automatically grabs the focus.
  24434. By default this is set to true, but you might want a component which can
  24435. be focused, but where you don't want the user to be able to affect it directly
  24436. by clicking.
  24437. */
  24438. void setMouseClickGrabsKeyboardFocus (bool shouldGrabFocus);
  24439. /** Returns the last value set with setMouseClickGrabsKeyboardFocus().
  24440. See setMouseClickGrabsKeyboardFocus() for more info.
  24441. */
  24442. bool getMouseClickGrabsKeyboardFocus() const noexcept;
  24443. /** Tries to give keyboard focus to this component.
  24444. When the user clicks on a component or its grabKeyboardFocus()
  24445. method is called, the following procedure is used to work out which
  24446. component should get it:
  24447. - if the component that was clicked on actually wants focus (as indicated
  24448. by calling getWantsKeyboardFocus), it gets it.
  24449. - if the component itself doesn't want focus, it will try to pass it
  24450. on to whichever of its children is the default component, as determined by
  24451. KeyboardFocusTraverser::getDefaultComponent()
  24452. - if none of its children want focus at all, it will pass it up to its
  24453. parent instead, unless it's a top-level component without a parent,
  24454. in which case it just takes the focus itself.
  24455. @see setWantsKeyboardFocus, getWantsKeyboardFocus, hasKeyboardFocus,
  24456. getCurrentlyFocusedComponent, focusGained, focusLost,
  24457. keyPressed, keyStateChanged
  24458. */
  24459. void grabKeyboardFocus();
  24460. /** Returns true if this component currently has the keyboard focus.
  24461. @param trueIfChildIsFocused if this is true, then the method returns true if
  24462. either this component or any of its children (recursively)
  24463. have the focus. If false, the method only returns true if
  24464. this component has the focus.
  24465. @see grabKeyboardFocus, setWantsKeyboardFocus, getCurrentlyFocusedComponent,
  24466. focusGained, focusLost
  24467. */
  24468. bool hasKeyboardFocus (bool trueIfChildIsFocused) const;
  24469. /** Returns the component that currently has the keyboard focus.
  24470. @returns the focused component, or null if nothing is focused.
  24471. */
  24472. static Component* JUCE_CALLTYPE getCurrentlyFocusedComponent() noexcept;
  24473. /** Tries to move the keyboard focus to one of this component's siblings.
  24474. This will try to move focus to either the next or previous component. (This
  24475. is the method that is used when shifting focus by pressing the tab key).
  24476. Components for which getWantsKeyboardFocus() returns false are not looked at.
  24477. @param moveToNext if true, the focus will move forwards; if false, it will
  24478. move backwards
  24479. @see grabKeyboardFocus, setFocusContainer, setWantsKeyboardFocus
  24480. */
  24481. void moveKeyboardFocusToSibling (bool moveToNext);
  24482. /** Creates a KeyboardFocusTraverser object to use to determine the logic by
  24483. which focus should be passed from this component.
  24484. The default implementation of this method will return a default
  24485. KeyboardFocusTraverser if this component is a focus container (as determined
  24486. by the setFocusContainer() method). If the component isn't a focus
  24487. container, then it will recursively ask its parents for a KeyboardFocusTraverser.
  24488. If you overrride this to return a custom KeyboardFocusTraverser, then
  24489. this component and all its sub-components will use the new object to
  24490. make their focusing decisions.
  24491. The method should return a new object, which the caller is required to
  24492. delete when no longer needed.
  24493. */
  24494. virtual KeyboardFocusTraverser* createFocusTraverser();
  24495. /** Returns the focus order of this component, if one has been specified.
  24496. By default components don't have a focus order - in that case, this
  24497. will return 0. Lower numbers indicate that the component will be
  24498. earlier in the focus traversal order.
  24499. To change the order, call setExplicitFocusOrder().
  24500. The focus order may be used by the KeyboardFocusTraverser class as part of
  24501. its algorithm for deciding the order in which components should be traversed.
  24502. See the KeyboardFocusTraverser class for more details on this.
  24503. @see moveKeyboardFocusToSibling, createFocusTraverser, KeyboardFocusTraverser
  24504. */
  24505. int getExplicitFocusOrder() const;
  24506. /** Sets the index used in determining the order in which focusable components
  24507. should be traversed.
  24508. A value of 0 or less is taken to mean that no explicit order is wanted, and
  24509. that traversal should use other factors, like the component's position.
  24510. @see getExplicitFocusOrder, moveKeyboardFocusToSibling
  24511. */
  24512. void setExplicitFocusOrder (int newFocusOrderIndex);
  24513. /** Indicates whether this component is a parent for components that can have
  24514. their focus traversed.
  24515. This flag is used by the default implementation of the createFocusTraverser()
  24516. method, which uses the flag to find the first parent component (of the currently
  24517. focused one) which wants to be a focus container.
  24518. So using this method to set the flag to 'true' causes this component to
  24519. act as the top level within which focus is passed around.
  24520. @see isFocusContainer, createFocusTraverser, moveKeyboardFocusToSibling
  24521. */
  24522. void setFocusContainer (bool shouldBeFocusContainer) noexcept;
  24523. /** Returns true if this component has been marked as a focus container.
  24524. See setFocusContainer() for more details.
  24525. @see setFocusContainer, moveKeyboardFocusToSibling, createFocusTraverser
  24526. */
  24527. bool isFocusContainer() const noexcept;
  24528. /** Returns true if the component (and all its parents) are enabled.
  24529. Components are enabled by default, and can be disabled with setEnabled(). Exactly
  24530. what difference this makes to the component depends on the type. E.g. buttons
  24531. and sliders will choose to draw themselves differently, etc.
  24532. Note that if one of this component's parents is disabled, this will always
  24533. return false, even if this component itself is enabled.
  24534. @see setEnabled, enablementChanged
  24535. */
  24536. bool isEnabled() const noexcept;
  24537. /** Enables or disables this component.
  24538. Disabling a component will also cause all of its child components to become
  24539. disabled.
  24540. Similarly, enabling a component which is inside a disabled parent
  24541. component won't make any difference until the parent is re-enabled.
  24542. @see isEnabled, enablementChanged
  24543. */
  24544. void setEnabled (bool shouldBeEnabled);
  24545. /** Callback to indicate that this component has been enabled or disabled.
  24546. This can be triggered by one of the component's parent components
  24547. being enabled or disabled, as well as changes to the component itself.
  24548. The default implementation of this method does nothing; your class may
  24549. wish to repaint itself or something when this happens.
  24550. @see setEnabled, isEnabled
  24551. */
  24552. virtual void enablementChanged();
  24553. /** Changes the transparency of this component.
  24554. When painted, the entire component and all its children will be rendered
  24555. with this as the overall opacity level, where 0 is completely invisible, and
  24556. 1.0 is fully opaque (i.e. normal).
  24557. @see getAlpha
  24558. */
  24559. void setAlpha (float newAlpha);
  24560. /** Returns the component's current transparancy level.
  24561. See setAlpha() for more details.
  24562. */
  24563. float getAlpha() const;
  24564. /** Changes the mouse cursor shape to use when the mouse is over this component.
  24565. Note that the cursor set by this method can be overridden by the getMouseCursor
  24566. method.
  24567. @see MouseCursor
  24568. */
  24569. void setMouseCursor (const MouseCursor& cursorType);
  24570. /** Returns the mouse cursor shape to use when the mouse is over this component.
  24571. The default implementation will return the cursor that was set by setCursor()
  24572. but can be overridden for more specialised purposes, e.g. returning different
  24573. cursors depending on the mouse position.
  24574. @see MouseCursor
  24575. */
  24576. virtual const MouseCursor getMouseCursor();
  24577. /** Forces the current mouse cursor to be updated.
  24578. If you're overriding the getMouseCursor() method to control which cursor is
  24579. displayed, then this will only be checked each time the user moves the mouse. So
  24580. if you want to force the system to check that the cursor being displayed is
  24581. up-to-date (even if the mouse is just sitting there), call this method.
  24582. (If you're changing the cursor using setMouseCursor(), you don't need to bother
  24583. calling this).
  24584. */
  24585. void updateMouseCursor() const;
  24586. /** Components can override this method to draw their content.
  24587. The paint() method gets called when a region of a component needs redrawing,
  24588. either because the component's repaint() method has been called, or because
  24589. something has happened on the screen that means a section of a window needs
  24590. to be redrawn.
  24591. Any child components will draw themselves over whatever this method draws. If
  24592. you need to paint over the top of your child components, you can also implement
  24593. the paintOverChildren() method to do this.
  24594. If you want to cause a component to redraw itself, this is done asynchronously -
  24595. calling the repaint() method marks a region of the component as "dirty", and the
  24596. paint() method will automatically be called sometime later, by the message thread,
  24597. to paint any bits that need refreshing. In Juce (and almost all modern UI frameworks),
  24598. you never redraw something synchronously.
  24599. You should never need to call this method directly - to take a snapshot of the
  24600. component you could use createComponentSnapshot() or paintEntireComponent().
  24601. @param g the graphics context that must be used to do the drawing operations.
  24602. @see repaint, paintOverChildren, Graphics
  24603. */
  24604. virtual void paint (Graphics& g);
  24605. /** Components can override this method to draw over the top of their children.
  24606. For most drawing operations, it's better to use the normal paint() method,
  24607. but if you need to overlay something on top of the children, this can be
  24608. used.
  24609. @see paint, Graphics
  24610. */
  24611. virtual void paintOverChildren (Graphics& g);
  24612. /** Called when the mouse moves inside this component.
  24613. If the mouse button isn't pressed and the mouse moves over a component,
  24614. this will be called to let the component react to this.
  24615. A component will always get a mouseEnter callback before a mouseMove.
  24616. @param e details about the position and status of the mouse event
  24617. @see mouseEnter, mouseExit, mouseDrag, contains
  24618. */
  24619. virtual void mouseMove (const MouseEvent& e);
  24620. /** Called when the mouse first enters this component.
  24621. If the mouse button isn't pressed and the mouse moves into a component,
  24622. this will be called to let the component react to this.
  24623. When the mouse button is pressed and held down while being moved in
  24624. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  24625. mouseDrag messages are sent to the component that the mouse was originally
  24626. clicked on, until the button is released.
  24627. If you're writing a component that needs to repaint itself when the mouse
  24628. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  24629. method.
  24630. @param e details about the position and status of the mouse event
  24631. @see mouseExit, mouseDrag, mouseMove, contains
  24632. */
  24633. virtual void mouseEnter (const MouseEvent& e);
  24634. /** Called when the mouse moves out of this component.
  24635. This will be called when the mouse moves off the edge of this
  24636. component.
  24637. If the mouse button was pressed, and it was then dragged off the
  24638. edge of the component and released, then this callback will happen
  24639. when the button is released, after the mouseUp callback.
  24640. If you're writing a component that needs to repaint itself when the mouse
  24641. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  24642. method.
  24643. @param e details about the position and status of the mouse event
  24644. @see mouseEnter, mouseDrag, mouseMove, contains
  24645. */
  24646. virtual void mouseExit (const MouseEvent& e);
  24647. /** Called when a mouse button is pressed while it's over this component.
  24648. The MouseEvent object passed in contains lots of methods for finding out
  24649. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  24650. were held down at the time.
  24651. Once a button is held down, the mouseDrag method will be called when the
  24652. mouse moves, until the button is released.
  24653. @param e details about the position and status of the mouse event
  24654. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  24655. */
  24656. virtual void mouseDown (const MouseEvent& e);
  24657. /** Called when the mouse is moved while a button is held down.
  24658. When a mouse button is pressed inside a component, that component
  24659. receives mouseDrag callbacks each time the mouse moves, even if the
  24660. mouse strays outside the component's bounds.
  24661. If you want to be able to drag things off the edge of a component
  24662. and have the component scroll when you get to the edges, the
  24663. beginDragAutoRepeat() method might be useful.
  24664. @param e details about the position and status of the mouse event
  24665. @see mouseDown, mouseUp, mouseMove, contains, beginDragAutoRepeat
  24666. */
  24667. virtual void mouseDrag (const MouseEvent& e);
  24668. /** Called when a mouse button is released.
  24669. A mouseUp callback is sent to the component in which a button was pressed
  24670. even if the mouse is actually over a different component when the
  24671. button is released.
  24672. The MouseEvent object passed in contains lots of methods for finding out
  24673. which buttons were down just before they were released.
  24674. @param e details about the position and status of the mouse event
  24675. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  24676. */
  24677. virtual void mouseUp (const MouseEvent& e);
  24678. /** Called when a mouse button has been double-clicked in this component.
  24679. The MouseEvent object passed in contains lots of methods for finding out
  24680. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  24681. were held down at the time.
  24682. For altering the time limit used to detect double-clicks,
  24683. see MouseEvent::setDoubleClickTimeout.
  24684. @param e details about the position and status of the mouse event
  24685. @see mouseDown, mouseUp, MouseEvent::setDoubleClickTimeout,
  24686. MouseEvent::getDoubleClickTimeout
  24687. */
  24688. virtual void mouseDoubleClick (const MouseEvent& e);
  24689. /** Called when the mouse-wheel is moved.
  24690. This callback is sent to the component that the mouse is over when the
  24691. wheel is moved.
  24692. If not overridden, the component will forward this message to its parent, so
  24693. that parent components can collect mouse-wheel messages that happen to
  24694. child components which aren't interested in them.
  24695. @param e details about the position and status of the mouse event
  24696. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  24697. value means the wheel has been pushed to the right, negative means it
  24698. was pushed to the left
  24699. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  24700. value means the wheel has been pushed upwards, negative means it
  24701. was pushed downwards
  24702. */
  24703. virtual void mouseWheelMove (const MouseEvent& e,
  24704. float wheelIncrementX,
  24705. float wheelIncrementY);
  24706. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  24707. current mouse-drag operation.
  24708. This allows you to make sure that mouseDrag() events are sent continuously, even
  24709. when the mouse isn't moving. This can be useful for things like auto-scrolling
  24710. components when the mouse is near an edge.
  24711. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  24712. minimum interval between consecutive mouse drag callbacks. The callbacks
  24713. will continue until the mouse is released, and then the interval will be reset,
  24714. so you need to make sure it's called every time you begin a drag event.
  24715. Passing an interval of 0 or less will cancel the auto-repeat.
  24716. @see mouseDrag, Desktop::beginDragAutoRepeat
  24717. */
  24718. static void beginDragAutoRepeat (int millisecondsBetweenCallbacks);
  24719. /** Causes automatic repaints when the mouse enters or exits this component.
  24720. If turned on, then when the mouse enters/exits, or when the button is pressed/released
  24721. on the component, it will trigger a repaint.
  24722. This is handy for things like buttons that need to draw themselves differently when
  24723. the mouse moves over them, and it avoids having to override all the different mouse
  24724. callbacks and call repaint().
  24725. @see mouseEnter, mouseExit, mouseDown, mouseUp
  24726. */
  24727. void setRepaintsOnMouseActivity (bool shouldRepaint) noexcept;
  24728. /** Registers a listener to be told when mouse events occur in this component.
  24729. If you need to get informed about mouse events in a component but can't or
  24730. don't want to override its methods, you can attach any number of listeners
  24731. to the component, and these will get told about the events in addition to
  24732. the component's own callbacks being called.
  24733. Note that a MouseListener can also be attached to more than one component.
  24734. @param newListener the listener to register
  24735. @param wantsEventsForAllNestedChildComponents if true, the listener will receive callbacks
  24736. for events that happen to any child component
  24737. within this component, including deeply-nested
  24738. child components. If false, it will only be
  24739. told about events that this component handles.
  24740. @see MouseListener, removeMouseListener
  24741. */
  24742. void addMouseListener (MouseListener* newListener,
  24743. bool wantsEventsForAllNestedChildComponents);
  24744. /** Deregisters a mouse listener.
  24745. @see addMouseListener, MouseListener
  24746. */
  24747. void removeMouseListener (MouseListener* listenerToRemove);
  24748. /** Adds a listener that wants to hear about keypresses that this component receives.
  24749. The listeners that are registered with a component are called by its keyPressed() or
  24750. keyStateChanged() methods (assuming these haven't been overridden to do something else).
  24751. If you add an object as a key listener, be careful to remove it when the object
  24752. is deleted, or the component will be left with a dangling pointer.
  24753. @see keyPressed, keyStateChanged, removeKeyListener
  24754. */
  24755. void addKeyListener (KeyListener* newListener);
  24756. /** Removes a previously-registered key listener.
  24757. @see addKeyListener
  24758. */
  24759. void removeKeyListener (KeyListener* listenerToRemove);
  24760. /** Called when a key is pressed.
  24761. When a key is pressed, the component that has the keyboard focus will have this
  24762. method called. Remember that a component will only be given the focus if its
  24763. setWantsKeyboardFocus() method has been used to enable this.
  24764. If your implementation returns true, the event will be consumed and not passed
  24765. on to any other listeners. If it returns false, the key will be passed to any
  24766. KeyListeners that have been registered with this component. As soon as one of these
  24767. returns true, the process will stop, but if they all return false, the event will
  24768. be passed upwards to this component's parent, and so on.
  24769. The default implementation of this method does nothing and returns false.
  24770. @see keyStateChanged, getCurrentlyFocusedComponent, addKeyListener
  24771. */
  24772. virtual bool keyPressed (const KeyPress& key);
  24773. /** Called when a key is pressed or released.
  24774. Whenever a key on the keyboard is pressed or released (including modifier keys
  24775. like shift and ctrl), this method will be called on the component that currently
  24776. has the keyboard focus. Remember that a component will only be given the focus if
  24777. its setWantsKeyboardFocus() method has been used to enable this.
  24778. If your implementation returns true, the event will be consumed and not passed
  24779. on to any other listeners. If it returns false, then any KeyListeners that have
  24780. been registered with this component will have their keyStateChanged methods called.
  24781. As soon as one of these returns true, the process will stop, but if they all return
  24782. false, the event will be passed upwards to this component's parent, and so on.
  24783. The default implementation of this method does nothing and returns false.
  24784. To find out which keys are up or down at any time, see the KeyPress::isKeyCurrentlyDown()
  24785. method.
  24786. @param isKeyDown true if a key has been pressed; false if it has been released
  24787. @see keyPressed, KeyPress, getCurrentlyFocusedComponent, addKeyListener
  24788. */
  24789. virtual bool keyStateChanged (bool isKeyDown);
  24790. /** Called when a modifier key is pressed or released.
  24791. Whenever the shift, control, alt or command keys are pressed or released,
  24792. this method will be called on the component that currently has the keyboard focus.
  24793. Remember that a component will only be given the focus if its setWantsKeyboardFocus()
  24794. method has been used to enable this.
  24795. The default implementation of this method actually calls its parent's modifierKeysChanged
  24796. method, so that focused components which aren't interested in this will give their
  24797. parents a chance to act on the event instead.
  24798. @see keyStateChanged, ModifierKeys
  24799. */
  24800. virtual void modifierKeysChanged (const ModifierKeys& modifiers);
  24801. /** Enumeration used by the focusChanged() and focusLost() methods. */
  24802. enum FocusChangeType
  24803. {
  24804. focusChangedByMouseClick, /**< Means that the user clicked the mouse to change focus. */
  24805. focusChangedByTabKey, /**< Means that the user pressed the tab key to move the focus. */
  24806. focusChangedDirectly /**< Means that the focus was changed by a call to grabKeyboardFocus(). */
  24807. };
  24808. /** Called to indicate that this component has just acquired the keyboard focus.
  24809. @see focusLost, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  24810. */
  24811. virtual void focusGained (FocusChangeType cause);
  24812. /** Called to indicate that this component has just lost the keyboard focus.
  24813. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  24814. */
  24815. virtual void focusLost (FocusChangeType cause);
  24816. /** Called to indicate that one of this component's children has been focused or unfocused.
  24817. Essentially this means that the return value of a call to hasKeyboardFocus (true) has
  24818. changed. It happens when focus moves from one of this component's children (at any depth)
  24819. to a component that isn't contained in this one, (or vice-versa).
  24820. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  24821. */
  24822. virtual void focusOfChildComponentChanged (FocusChangeType cause);
  24823. /** Returns true if the mouse is currently over this component.
  24824. If the mouse isn't over the component, this will return false, even if the
  24825. mouse is currently being dragged - so you can use this in your mouseDrag
  24826. method to find out whether it's really over the component or not.
  24827. Note that when the mouse button is being held down, then the only component
  24828. for which this method will return true is the one that was originally
  24829. clicked on.
  24830. If includeChildren is true, then this will also return true if the mouse is over
  24831. any of the component's children (recursively) as well as the component itself.
  24832. @see isMouseButtonDown. isMouseOverOrDragging, mouseDrag
  24833. */
  24834. bool isMouseOver (bool includeChildren = false) const;
  24835. /** Returns true if the mouse button is currently held down in this component.
  24836. Note that this is a test to see whether the mouse is being pressed in this
  24837. component, so it'll return false if called on component A when the mouse
  24838. is actually being dragged in component B.
  24839. @see isMouseButtonDownAnywhere, isMouseOver, isMouseOverOrDragging
  24840. */
  24841. bool isMouseButtonDown() const noexcept;
  24842. /** True if the mouse is over this component, or if it's being dragged in this component.
  24843. This is a handy equivalent to (isMouseOver() || isMouseButtonDown()).
  24844. @see isMouseOver, isMouseButtonDown, isMouseButtonDownAnywhere
  24845. */
  24846. bool isMouseOverOrDragging() const noexcept;
  24847. /** Returns true if a mouse button is currently down.
  24848. Unlike isMouseButtonDown, this will test the current state of the
  24849. buttons without regard to which component (if any) it has been
  24850. pressed in.
  24851. @see isMouseButtonDown, ModifierKeys
  24852. */
  24853. static bool JUCE_CALLTYPE isMouseButtonDownAnywhere() noexcept;
  24854. /** Returns the mouse's current position, relative to this component.
  24855. The return value is relative to the component's top-left corner.
  24856. */
  24857. Point<int> getMouseXYRelative() const;
  24858. /** Called when this component's size has been changed.
  24859. A component can implement this method to do things such as laying out its
  24860. child components when its width or height changes.
  24861. The method is called synchronously as a result of the setBounds or setSize
  24862. methods, so repeatedly changing a components size will repeatedly call its
  24863. resized method (unlike things like repainting, where multiple calls to repaint
  24864. are coalesced together).
  24865. If the component is a top-level window on the desktop, its size could also
  24866. be changed by operating-system factors beyond the application's control.
  24867. @see moved, setSize
  24868. */
  24869. virtual void resized();
  24870. /** Called when this component's position has been changed.
  24871. This is called when the position relative to its parent changes, not when
  24872. its absolute position on the screen changes (so it won't be called for
  24873. all child components when a parent component is moved).
  24874. The method is called synchronously as a result of the setBounds, setTopLeftPosition
  24875. or any of the other repositioning methods, and like resized(), it will be
  24876. called each time those methods are called.
  24877. If the component is a top-level window on the desktop, its position could also
  24878. be changed by operating-system factors beyond the application's control.
  24879. @see resized, setBounds
  24880. */
  24881. virtual void moved();
  24882. /** Called when one of this component's children is moved or resized.
  24883. If the parent wants to know about changes to its immediate children (not
  24884. to children of its children), this is the method to override.
  24885. @see moved, resized, parentSizeChanged
  24886. */
  24887. virtual void childBoundsChanged (Component* child);
  24888. /** Called when this component's immediate parent has been resized.
  24889. If the component is a top-level window, this indicates that the screen size
  24890. has changed.
  24891. @see childBoundsChanged, moved, resized
  24892. */
  24893. virtual void parentSizeChanged();
  24894. /** Called when this component has been moved to the front of its siblings.
  24895. The component may have been brought to the front by the toFront() method, or
  24896. by the operating system if it's a top-level window.
  24897. @see toFront
  24898. */
  24899. virtual void broughtToFront();
  24900. /** Adds a listener to be told about changes to the component hierarchy or position.
  24901. Component listeners get called when this component's size, position or children
  24902. change - see the ComponentListener class for more details.
  24903. @param newListener the listener to register - if this is already registered, it
  24904. will be ignored.
  24905. @see ComponentListener, removeComponentListener
  24906. */
  24907. void addComponentListener (ComponentListener* newListener);
  24908. /** Removes a component listener.
  24909. @see addComponentListener
  24910. */
  24911. void removeComponentListener (ComponentListener* listenerToRemove);
  24912. /** Dispatches a numbered message to this component.
  24913. This is a quick and cheap way of allowing simple asynchronous messages to
  24914. be sent to components. It's also safe, because if the component that you
  24915. send the message to is a null or dangling pointer, this won't cause an error.
  24916. The command ID is later delivered to the component's handleCommandMessage() method by
  24917. the application's message queue.
  24918. @see handleCommandMessage
  24919. */
  24920. void postCommandMessage (int commandId);
  24921. /** Called to handle a command that was sent by postCommandMessage().
  24922. This is called by the message thread when a command message arrives, and
  24923. the component can override this method to process it in any way it needs to.
  24924. @see postCommandMessage
  24925. */
  24926. virtual void handleCommandMessage (int commandId);
  24927. /** Runs a component modally, waiting until the loop terminates.
  24928. This method first makes the component visible, brings it to the front and
  24929. gives it the keyboard focus.
  24930. It then runs a loop, dispatching messages from the system message queue, but
  24931. blocking all mouse or keyboard messages from reaching any components other
  24932. than this one and its children.
  24933. This loop continues until the component's exitModalState() method is called (or
  24934. the component is deleted), and then this method returns, returning the value
  24935. passed into exitModalState().
  24936. @see enterModalState, exitModalState, isCurrentlyModal, getCurrentlyModalComponent,
  24937. isCurrentlyBlockedByAnotherModalComponent, ModalComponentManager
  24938. */
  24939. #if JUCE_MODAL_LOOPS_PERMITTED
  24940. int runModalLoop();
  24941. #endif
  24942. /** Puts the component into a modal state.
  24943. This makes the component modal, so that messages are blocked from reaching
  24944. any components other than this one and its children, but unlike runModalLoop(),
  24945. this method returns immediately.
  24946. If takeKeyboardFocus is true, the component will use grabKeyboardFocus() to
  24947. get the focus, which is usually what you'll want it to do. If not, it will leave
  24948. the focus unchanged.
  24949. The callback is an optional object which will receive a callback when the modal
  24950. component loses its modal status, either by being hidden or when exitModalState()
  24951. is called. If you pass an object in here, the system will take care of deleting it
  24952. later, after making the callback
  24953. If deleteWhenDismissed is true, then when it is dismissed, the component will be
  24954. deleted and then the callback will be called. (This will safely handle the situation
  24955. where the component is deleted before its exitModalState() method is called).
  24956. @see exitModalState, runModalLoop, ModalComponentManager::attachCallback
  24957. */
  24958. void enterModalState (bool takeKeyboardFocus = true,
  24959. ModalComponentManager::Callback* callback = nullptr,
  24960. bool deleteWhenDismissed = false);
  24961. /** Ends a component's modal state.
  24962. If this component is currently modal, this will turn of its modalness, and return
  24963. a value to the runModalLoop() method that might have be running its modal loop.
  24964. @see runModalLoop, enterModalState, isCurrentlyModal
  24965. */
  24966. void exitModalState (int returnValue);
  24967. /** Returns true if this component is the modal one.
  24968. It's possible to have nested modal components, e.g. a pop-up dialog box
  24969. that launches another pop-up, but this will only return true for
  24970. the one at the top of the stack.
  24971. @see getCurrentlyModalComponent
  24972. */
  24973. bool isCurrentlyModal() const noexcept;
  24974. /** Returns the number of components that are currently in a modal state.
  24975. @see getCurrentlyModalComponent
  24976. */
  24977. static int JUCE_CALLTYPE getNumCurrentlyModalComponents() noexcept;
  24978. /** Returns one of the components that are currently modal.
  24979. The index specifies which of the possible modal components to return. The order
  24980. of the components in this list is the reverse of the order in which they became
  24981. modal - so the component at index 0 is always the active component, and the others
  24982. are progressively earlier ones that are themselves now blocked by later ones.
  24983. @returns the modal component, or null if no components are modal (or if the
  24984. index is out of range)
  24985. @see getNumCurrentlyModalComponents, runModalLoop, isCurrentlyModal
  24986. */
  24987. static Component* JUCE_CALLTYPE getCurrentlyModalComponent (int index = 0) noexcept;
  24988. /** Checks whether there's a modal component somewhere that's stopping this one
  24989. from receiving messages.
  24990. If there is a modal component, its canModalEventBeSentToComponent() method
  24991. will be called to see if it will still allow this component to receive events.
  24992. @see runModalLoop, getCurrentlyModalComponent
  24993. */
  24994. bool isCurrentlyBlockedByAnotherModalComponent() const;
  24995. /** When a component is modal, this callback allows it to choose which other
  24996. components can still receive events.
  24997. When a modal component is active and the user clicks on a non-modal component,
  24998. this method is called on the modal component, and if it returns true, the
  24999. event is allowed to reach its target. If it returns false, the event is blocked
  25000. and the inputAttemptWhenModal() callback is made.
  25001. It called by the isCurrentlyBlockedByAnotherModalComponent() method. The default
  25002. implementation just returns false in all cases.
  25003. */
  25004. virtual bool canModalEventBeSentToComponent (const Component* targetComponent);
  25005. /** Called when the user tries to click on a component that is blocked by another
  25006. modal component.
  25007. When a component is modal and the user clicks on one of the other components,
  25008. the modal component will receive this callback.
  25009. The default implementation of this method will play a beep, and bring the currently
  25010. modal component to the front, but it can be overridden to do other tasks.
  25011. @see isCurrentlyBlockedByAnotherModalComponent, canModalEventBeSentToComponent
  25012. */
  25013. virtual void inputAttemptWhenModal();
  25014. /** Returns the set of properties that belong to this component.
  25015. Each component has a NamedValueSet object which you can use to attach arbitrary
  25016. items of data to it.
  25017. */
  25018. NamedValueSet& getProperties() noexcept { return properties; }
  25019. /** Returns the set of properties that belong to this component.
  25020. Each component has a NamedValueSet object which you can use to attach arbitrary
  25021. items of data to it.
  25022. */
  25023. const NamedValueSet& getProperties() const noexcept { return properties; }
  25024. /** Looks for a colour that has been registered with the given colour ID number.
  25025. If a colour has been set for this ID number using setColour(), then it is
  25026. returned. If none has been set, the method will try calling the component's
  25027. LookAndFeel class's findColour() method. If none has been registered with the
  25028. look-and-feel either, it will just return black.
  25029. The colour IDs for various purposes are stored as enums in the components that
  25030. they are relevent to - for an example, see Slider::ColourIds,
  25031. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  25032. @see setColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  25033. */
  25034. const Colour findColour (int colourId, bool inheritFromParent = false) const;
  25035. /** Registers a colour to be used for a particular purpose.
  25036. Changing a colour will cause a synchronous callback to the colourChanged()
  25037. method, which your component can override if it needs to do something when
  25038. colours are altered.
  25039. For more details about colour IDs, see the comments for findColour().
  25040. @see findColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  25041. */
  25042. void setColour (int colourId, const Colour& colour);
  25043. /** If a colour has been set with setColour(), this will remove it.
  25044. This allows you to make a colour revert to its default state.
  25045. */
  25046. void removeColour (int colourId);
  25047. /** Returns true if the specified colour ID has been explicitly set for this
  25048. component using the setColour() method.
  25049. */
  25050. bool isColourSpecified (int colourId) const;
  25051. /** This looks for any colours that have been specified for this component,
  25052. and copies them to the specified target component.
  25053. */
  25054. void copyAllExplicitColoursTo (Component& target) const;
  25055. /** This method is called when a colour is changed by the setColour() method.
  25056. @see setColour, findColour
  25057. */
  25058. virtual void colourChanged();
  25059. /** Components can implement this method to provide a MarkerList.
  25060. The default implementation of this method returns 0, but you can override it to
  25061. return a pointer to the component's marker list. If xAxis is true, it should
  25062. return the X marker list; if false, it should return the Y markers.
  25063. */
  25064. virtual MarkerList* getMarkers (bool xAxis);
  25065. /** Returns the underlying native window handle for this component.
  25066. This is platform-dependent and strictly for power-users only!
  25067. */
  25068. void* getWindowHandle() const;
  25069. /** Holds a pointer to some type of Component, which automatically becomes null if
  25070. the component is deleted.
  25071. If you're using a component which may be deleted by another event that's outside
  25072. of your control, use a SafePointer instead of a normal pointer to refer to it,
  25073. and you can test whether it's null before using it to see if something has deleted
  25074. it.
  25075. The ComponentType typedef must be Component, or some subclass of Component.
  25076. You may also want to use a WeakReference<Component> object for the same purpose.
  25077. */
  25078. template <class ComponentType>
  25079. class SafePointer
  25080. {
  25081. public:
  25082. /** Creates a null SafePointer. */
  25083. SafePointer() noexcept {}
  25084. /** Creates a SafePointer that points at the given component. */
  25085. SafePointer (ComponentType* const component) : weakRef (component) {}
  25086. /** Creates a copy of another SafePointer. */
  25087. SafePointer (const SafePointer& other) noexcept : weakRef (other.weakRef) {}
  25088. /** Copies another pointer to this one. */
  25089. SafePointer& operator= (const SafePointer& other) { weakRef = other.weakRef; return *this; }
  25090. /** Copies another pointer to this one. */
  25091. SafePointer& operator= (ComponentType* const newComponent) { weakRef = newComponent; return *this; }
  25092. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  25093. ComponentType* getComponent() const noexcept { return dynamic_cast <ComponentType*> (weakRef.get()); }
  25094. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  25095. operator ComponentType*() const noexcept { return getComponent(); }
  25096. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  25097. ComponentType* operator->() noexcept { return getComponent(); }
  25098. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  25099. const ComponentType* operator->() const noexcept { return getComponent(); }
  25100. /** If the component is valid, this deletes it and sets this pointer to null. */
  25101. void deleteAndZero() { delete getComponent(); jassert (getComponent() == nullptr); }
  25102. bool operator== (ComponentType* component) const noexcept { return weakRef == component; }
  25103. bool operator!= (ComponentType* component) const noexcept { return weakRef != component; }
  25104. private:
  25105. WeakReference<Component> weakRef;
  25106. };
  25107. /** A class to keep an eye on a component and check for it being deleted.
  25108. This is designed for use with the ListenerList::callChecked() methods, to allow
  25109. the list iterator to stop cleanly if the component is deleted by a listener callback
  25110. while the list is still being iterated.
  25111. */
  25112. class JUCE_API BailOutChecker
  25113. {
  25114. public:
  25115. /** Creates a checker that watches one component. */
  25116. BailOutChecker (Component* component);
  25117. /** Returns true if either of the two components have been deleted since this object was created. */
  25118. bool shouldBailOut() const noexcept;
  25119. private:
  25120. const WeakReference<Component> safePointer;
  25121. JUCE_DECLARE_NON_COPYABLE (BailOutChecker);
  25122. };
  25123. /**
  25124. Base class for objects that can be used to automatically position a component according to
  25125. some kind of algorithm.
  25126. The component class simply holds onto a reference to a Positioner, but doesn't actually do
  25127. anything with it - all the functionality must be implemented by the positioner itself (e.g.
  25128. it might choose to watch some kind of value and move the component when the value changes).
  25129. */
  25130. class JUCE_API Positioner
  25131. {
  25132. public:
  25133. /** Creates a Positioner which can control the specified component. */
  25134. explicit Positioner (Component& component) noexcept;
  25135. /** Destructor. */
  25136. virtual ~Positioner() {}
  25137. /** Returns the component that this positioner controls. */
  25138. Component& getComponent() const noexcept { return component; }
  25139. /** Attempts to set the component's position to the given rectangle.
  25140. Unlike simply calling Component::setBounds(), this may involve the positioner
  25141. being smart enough to adjust itself to fit the new bounds, e.g. a RelativeRectangle's
  25142. positioner may try to reverse the expressions used to make them fit these new coordinates.
  25143. */
  25144. virtual void applyNewBounds (const Rectangle<int>& newBounds) = 0;
  25145. private:
  25146. Component& component;
  25147. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Positioner);
  25148. };
  25149. /** Returns the Positioner object that has been set for this component.
  25150. @see setPositioner()
  25151. */
  25152. Positioner* getPositioner() const noexcept;
  25153. /** Sets a new Positioner object for this component.
  25154. If there's currently another positioner set, it will be deleted. The object that is passed in
  25155. will be deleted automatically by this component when it's no longer required. Pass a null pointer
  25156. to clear the current positioner.
  25157. @see getPositioner()
  25158. */
  25159. void setPositioner (Positioner* newPositioner);
  25160. #ifndef DOXYGEN
  25161. // These methods are deprecated - use localPointToGlobal, getLocalPoint, getLocalPoint, etc instead.
  25162. JUCE_DEPRECATED (const Point<int> relativePositionToGlobal (const Point<int>&) const);
  25163. JUCE_DEPRECATED (const Point<int> globalPositionToRelative (const Point<int>&) const);
  25164. JUCE_DEPRECATED (const Point<int> relativePositionToOtherComponent (const Component*, const Point<int>&) const);
  25165. #endif
  25166. private:
  25167. friend class ComponentPeer;
  25168. friend class MouseInputSource;
  25169. friend class MouseInputSourceInternal;
  25170. #ifndef DOXYGEN
  25171. static Component* currentlyFocusedComponent;
  25172. String componentName, componentID;
  25173. Component* parentComponent;
  25174. Rectangle<int> bounds;
  25175. ScopedPointer <Positioner> positioner;
  25176. ScopedPointer <AffineTransform> affineTransform;
  25177. Array <Component*> childComponentList;
  25178. LookAndFeel* lookAndFeel;
  25179. MouseCursor cursor;
  25180. ImageEffectFilter* effect;
  25181. Image bufferedImage;
  25182. class MouseListenerList;
  25183. friend class MouseListenerList;
  25184. friend class ScopedPointer <MouseListenerList>;
  25185. ScopedPointer <MouseListenerList> mouseListeners;
  25186. ScopedPointer <Array <KeyListener*> > keyListeners;
  25187. ListenerList <ComponentListener> componentListeners;
  25188. NamedValueSet properties;
  25189. friend class WeakReference<Component>;
  25190. WeakReference<Component>::Master weakReferenceMaster;
  25191. const WeakReference<Component>::SharedRef& getWeakReference();
  25192. struct ComponentFlags
  25193. {
  25194. bool hasHeavyweightPeerFlag : 1;
  25195. bool visibleFlag : 1;
  25196. bool opaqueFlag : 1;
  25197. bool ignoresMouseClicksFlag : 1;
  25198. bool allowChildMouseClicksFlag : 1;
  25199. bool wantsFocusFlag : 1;
  25200. bool isFocusContainerFlag : 1;
  25201. bool dontFocusOnMouseClickFlag : 1;
  25202. bool alwaysOnTopFlag : 1;
  25203. bool bufferToImageFlag : 1;
  25204. bool bringToFrontOnClickFlag : 1;
  25205. bool repaintOnMouseActivityFlag : 1;
  25206. bool mouseDownFlag : 1;
  25207. bool mouseOverFlag : 1;
  25208. bool mouseInsideFlag : 1;
  25209. bool currentlyModalFlag : 1;
  25210. bool isDisabledFlag : 1;
  25211. bool childCompFocusedFlag : 1;
  25212. bool dontClipGraphicsFlag : 1;
  25213. #if JUCE_DEBUG
  25214. bool isInsidePaintCall : 1;
  25215. #endif
  25216. };
  25217. union
  25218. {
  25219. uint32 componentFlags;
  25220. ComponentFlags flags;
  25221. };
  25222. uint8 componentTransparency;
  25223. void internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  25224. void internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  25225. void internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  25226. void internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers);
  25227. void internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  25228. void internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  25229. void internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos, const Time& time, float amountX, float amountY);
  25230. void internalBroughtToFront();
  25231. void internalFocusGain (const FocusChangeType cause, const WeakReference<Component>&);
  25232. void internalFocusGain (const FocusChangeType cause);
  25233. void internalFocusLoss (const FocusChangeType cause);
  25234. void internalChildFocusChange (FocusChangeType cause, const WeakReference<Component>&);
  25235. void internalModalInputAttempt();
  25236. void internalModifierKeysChanged();
  25237. void internalChildrenChanged();
  25238. void internalHierarchyChanged();
  25239. Component* removeChildComponent (int index, bool sendParentEvents, bool sendChildEvents);
  25240. void moveChildInternal (int sourceIndex, int destIndex);
  25241. void paintComponentAndChildren (Graphics& g);
  25242. void paintComponent (Graphics& g);
  25243. void paintWithinParentContext (Graphics& g);
  25244. void sendMovedResizedMessages (bool wasMoved, bool wasResized);
  25245. void repaintParent();
  25246. void sendFakeMouseMove() const;
  25247. void takeKeyboardFocus (const FocusChangeType cause);
  25248. void grabFocusInternal (const FocusChangeType cause, bool canTryParent = true);
  25249. static void giveAwayFocus (bool sendFocusLossEvent);
  25250. void sendEnablementChangeMessage();
  25251. void sendVisibilityChangeMessage();
  25252. class ComponentHelpers;
  25253. friend class ComponentHelpers;
  25254. /* Components aren't allowed to have copy constructors, as this would mess up parent hierarchies.
  25255. You might need to give your subclasses a private dummy constructor to avoid compiler warnings.
  25256. */
  25257. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Component);
  25258. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  25259. // This is included here just to cause a compile error if your code is still handling
  25260. // drag-and-drop with this method. If so, just update it to use the new FileDragAndDropTarget
  25261. // class, which is easy (just make your class inherit from FileDragAndDropTarget, and
  25262. // implement its methods instead of this Component method).
  25263. virtual void filesDropped (const StringArray&, int, int) {}
  25264. // This is included here to cause an error if you use or overload it - it has been deprecated in
  25265. // favour of contains (const Point<int>&)
  25266. void contains (int, int);
  25267. #endif
  25268. protected:
  25269. /** @internal */
  25270. virtual void internalRepaint (int x, int y, int w, int h);
  25271. /** @internal */
  25272. virtual ComponentPeer* createNewPeer (int styleFlags, void* nativeWindowToAttachTo);
  25273. #endif
  25274. };
  25275. #endif // __JUCE_COMPONENT_JUCEHEADER__
  25276. /*** End of inlined file: juce_Component.h ***/
  25277. /*** Start of inlined file: juce_ApplicationCommandInfo.h ***/
  25278. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  25279. #define __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  25280. /*** Start of inlined file: juce_ApplicationCommandID.h ***/
  25281. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  25282. #define __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  25283. /** A type used to hold the unique ID for an application command.
  25284. This is a numeric type, so it can be stored as an integer.
  25285. @see ApplicationCommandInfo, ApplicationCommandManager,
  25286. ApplicationCommandTarget, KeyPressMappingSet
  25287. */
  25288. typedef int CommandID;
  25289. /** A set of general-purpose application command IDs.
  25290. Because these commands are likely to be used in most apps, they're defined
  25291. here to help different apps to use the same numeric values for them.
  25292. Of course you don't have to use these, but some of them are used internally by
  25293. Juce - e.g. the quit ID is recognised as a command by the JUCEApplication class.
  25294. @see ApplicationCommandInfo, ApplicationCommandManager,
  25295. ApplicationCommandTarget, KeyPressMappingSet
  25296. */
  25297. namespace StandardApplicationCommandIDs
  25298. {
  25299. /** This command ID should be used to send a "Quit the App" command.
  25300. This command is recognised by the JUCEApplication class, so if it is invoked
  25301. and no other ApplicationCommandTarget handles the event first, the JUCEApplication
  25302. object will catch it and call JUCEApplication::systemRequestedQuit().
  25303. */
  25304. static const CommandID quit = 0x1001;
  25305. /** The command ID that should be used to send a "Delete" command. */
  25306. static const CommandID del = 0x1002;
  25307. /** The command ID that should be used to send a "Cut" command. */
  25308. static const CommandID cut = 0x1003;
  25309. /** The command ID that should be used to send a "Copy to clipboard" command. */
  25310. static const CommandID copy = 0x1004;
  25311. /** The command ID that should be used to send a "Paste from clipboard" command. */
  25312. static const CommandID paste = 0x1005;
  25313. /** The command ID that should be used to send a "Select all" command. */
  25314. static const CommandID selectAll = 0x1006;
  25315. /** The command ID that should be used to send a "Deselect all" command. */
  25316. static const CommandID deselectAll = 0x1007;
  25317. }
  25318. #endif // __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  25319. /*** End of inlined file: juce_ApplicationCommandID.h ***/
  25320. /**
  25321. Holds information describing an application command.
  25322. This object is used to pass information about a particular command, such as its
  25323. name, description and other usage flags.
  25324. When an ApplicationCommandTarget is asked to provide information about the commands
  25325. it can perform, this is the structure gets filled-in to describe each one.
  25326. @see ApplicationCommandTarget, ApplicationCommandTarget::getCommandInfo(),
  25327. ApplicationCommandManager
  25328. */
  25329. struct JUCE_API ApplicationCommandInfo
  25330. {
  25331. explicit ApplicationCommandInfo (CommandID commandID) noexcept;
  25332. /** Sets a number of the structures values at once.
  25333. The meanings of each of the parameters is described below, in the appropriate
  25334. member variable's description.
  25335. */
  25336. void setInfo (const String& shortName,
  25337. const String& description,
  25338. const String& categoryName,
  25339. int flags) noexcept;
  25340. /** An easy way to set or remove the isDisabled bit in the structure's flags field.
  25341. If isActive is true, the flags member has the isDisabled bit cleared; if isActive
  25342. is false, the bit is set.
  25343. */
  25344. void setActive (bool isActive) noexcept;
  25345. /** An easy way to set or remove the isTicked bit in the structure's flags field.
  25346. */
  25347. void setTicked (bool isTicked) noexcept;
  25348. /** Handy method for adding a keypress to the defaultKeypresses array.
  25349. This is just so you can write things like:
  25350. @code
  25351. myinfo.addDefaultKeypress ('s', ModifierKeys::commandModifier);
  25352. @endcode
  25353. instead of
  25354. @code
  25355. myinfo.defaultKeypresses.add (KeyPress ('s', ModifierKeys::commandModifier));
  25356. @endcode
  25357. */
  25358. void addDefaultKeypress (int keyCode,
  25359. const ModifierKeys& modifiers) noexcept;
  25360. /** The command's unique ID number.
  25361. */
  25362. CommandID commandID;
  25363. /** A short name to describe the command.
  25364. This should be suitable for use in menus, on buttons that trigger the command, etc.
  25365. You can use the setInfo() method to quickly set this and some of the command's
  25366. other properties.
  25367. */
  25368. String shortName;
  25369. /** A longer description of the command.
  25370. This should be suitable for use in contexts such as a KeyMappingEditorComponent or
  25371. pop-up tooltip describing what the command does.
  25372. You can use the setInfo() method to quickly set this and some of the command's
  25373. other properties.
  25374. */
  25375. String description;
  25376. /** A named category that the command fits into.
  25377. You can give your commands any category you like, and these will be displayed in
  25378. contexts such as the KeyMappingEditorComponent, where the category is used to group
  25379. commands together.
  25380. You can use the setInfo() method to quickly set this and some of the command's
  25381. other properties.
  25382. */
  25383. String categoryName;
  25384. /** A list of zero or more keypresses that should be used as the default keys for
  25385. this command.
  25386. Methods such as KeyPressMappingSet::resetToDefaultMappings() will use the keypresses in
  25387. this list to initialise the default set of key-to-command mappings.
  25388. @see addDefaultKeypress
  25389. */
  25390. Array <KeyPress> defaultKeypresses;
  25391. /** Flags describing the ways in which this command should be used.
  25392. A bitwise-OR of these values is stored in the ApplicationCommandInfo::flags
  25393. variable.
  25394. */
  25395. enum CommandFlags
  25396. {
  25397. /** Indicates that the command can't currently be performed.
  25398. The ApplicationCommandTarget::getCommandInfo() method must set this flag if it's
  25399. not currently permissable to perform the command. If the flag is set, then
  25400. components that trigger the command, e.g. PopupMenu, may choose to grey-out the
  25401. command or show themselves as not being enabled.
  25402. @see ApplicationCommandInfo::setActive
  25403. */
  25404. isDisabled = 1 << 0,
  25405. /** Indicates that the command should have a tick next to it on a menu.
  25406. If your command is shown on a menu and this is set, it'll show a tick next to
  25407. it. Other components such as buttons may also use this flag to indicate that it
  25408. is a value that can be toggled, and is currently in the 'on' state.
  25409. @see ApplicationCommandInfo::setTicked
  25410. */
  25411. isTicked = 1 << 1,
  25412. /** If this flag is present, then when a KeyPressMappingSet invokes the command,
  25413. it will call the command twice, once on key-down and again on key-up.
  25414. @see ApplicationCommandTarget::InvocationInfo
  25415. */
  25416. wantsKeyUpDownCallbacks = 1 << 2,
  25417. /** If this flag is present, then a KeyMappingEditorComponent will not display the
  25418. command in its list.
  25419. */
  25420. hiddenFromKeyEditor = 1 << 3,
  25421. /** If this flag is present, then a KeyMappingEditorComponent will display the
  25422. command in its list, but won't allow the assigned keypress to be changed.
  25423. */
  25424. readOnlyInKeyEditor = 1 << 4,
  25425. /** If this flag is present and the command is invoked from a keypress, then any
  25426. buttons or menus that are also connected to the command will not flash to
  25427. indicate that they've been triggered.
  25428. */
  25429. dontTriggerVisualFeedback = 1 << 5
  25430. };
  25431. /** A bitwise-OR of the values specified in the CommandFlags enum.
  25432. You can use the setInfo() method to quickly set this and some of the command's
  25433. other properties.
  25434. */
  25435. int flags;
  25436. };
  25437. #endif // __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  25438. /*** End of inlined file: juce_ApplicationCommandInfo.h ***/
  25439. /*** Start of inlined file: juce_MessageListener.h ***/
  25440. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  25441. #define __JUCE_MESSAGELISTENER_JUCEHEADER__
  25442. /**
  25443. MessageListener subclasses can post and receive Message objects.
  25444. @see Message, MessageManager, ActionListener, ChangeListener
  25445. */
  25446. class JUCE_API MessageListener
  25447. {
  25448. protected:
  25449. /** Creates a MessageListener. */
  25450. MessageListener() noexcept;
  25451. public:
  25452. /** Destructor.
  25453. When a MessageListener is deleted, it removes itself from a global list
  25454. of registered listeners, so that the isValidMessageListener() method
  25455. will no longer return true.
  25456. */
  25457. virtual ~MessageListener();
  25458. /** This is the callback method that receives incoming messages.
  25459. This is called by the MessageManager from its dispatch loop.
  25460. @see postMessage
  25461. */
  25462. virtual void handleMessage (const Message& message) = 0;
  25463. /** Sends a message to the message queue, for asynchronous delivery to this listener
  25464. later on.
  25465. This method can be called safely by any thread.
  25466. @param message the message object to send - this will be deleted
  25467. automatically by the message queue, so don't keep any
  25468. references to it after calling this method.
  25469. @see handleMessage
  25470. */
  25471. void postMessage (Message* message) const noexcept;
  25472. /** Checks whether this MessageListener has been deleted.
  25473. Although not foolproof, this method is safe to call on dangling or null
  25474. pointers. A list of active MessageListeners is kept internally, so this
  25475. checks whether the object is on this list or not.
  25476. Note that it's possible to get a false-positive here, if an object is
  25477. deleted and another is subsequently created that happens to be at the
  25478. exact same memory location, but I can't think of a good way of avoiding
  25479. this.
  25480. */
  25481. bool isValidMessageListener() const noexcept;
  25482. };
  25483. #endif // __JUCE_MESSAGELISTENER_JUCEHEADER__
  25484. /*** End of inlined file: juce_MessageListener.h ***/
  25485. /**
  25486. A command target publishes a list of command IDs that it can perform.
  25487. An ApplicationCommandManager despatches commands to targets, which must be
  25488. able to provide information about what commands they can handle.
  25489. To create a target, you'll need to inherit from this class, implementing all of
  25490. its pure virtual methods.
  25491. For info about how a target is chosen to receive a command, see
  25492. ApplicationCommandManager::getFirstCommandTarget().
  25493. @see ApplicationCommandManager, ApplicationCommandInfo
  25494. */
  25495. class JUCE_API ApplicationCommandTarget
  25496. {
  25497. public:
  25498. /** Creates a command target. */
  25499. ApplicationCommandTarget();
  25500. /** Destructor. */
  25501. virtual ~ApplicationCommandTarget();
  25502. /**
  25503. */
  25504. struct JUCE_API InvocationInfo
  25505. {
  25506. InvocationInfo (const CommandID commandID);
  25507. /** The UID of the command that should be performed. */
  25508. CommandID commandID;
  25509. /** The command's flags.
  25510. See ApplicationCommandInfo for a description of these flag values.
  25511. */
  25512. int commandFlags;
  25513. /** The types of context in which the command might be called. */
  25514. enum InvocationMethod
  25515. {
  25516. direct = 0, /**< The command is being invoked directly by a piece of code. */
  25517. fromKeyPress, /**< The command is being invoked by a key-press. */
  25518. fromMenu, /**< The command is being invoked by a menu selection. */
  25519. fromButton /**< The command is being invoked by a button click. */
  25520. };
  25521. /** The type of event that triggered this command. */
  25522. InvocationMethod invocationMethod;
  25523. /** If triggered by a keypress or menu, this will be the component that had the
  25524. keyboard focus at the time.
  25525. If triggered by a button, it may be set to that component, or it may be null.
  25526. */
  25527. Component* originatingComponent;
  25528. /** The keypress that was used to invoke it.
  25529. Note that this will be an invalid keypress if the command was invoked
  25530. by some other means than a keyboard shortcut.
  25531. */
  25532. KeyPress keyPress;
  25533. /** True if the callback is being invoked when the key is pressed,
  25534. false if the key is being released.
  25535. @see KeyPressMappingSet::addCommand()
  25536. */
  25537. bool isKeyDown;
  25538. /** If the key is being released, this indicates how long it had been held
  25539. down for.
  25540. (Only relevant if isKeyDown is false.)
  25541. */
  25542. int millisecsSinceKeyPressed;
  25543. };
  25544. /** This must return the next target to try after this one.
  25545. When a command is being sent, and the first target can't handle
  25546. that command, this method is used to determine the next target that should
  25547. be tried.
  25548. It may return 0 if it doesn't know of another target.
  25549. If your target is a Component, you would usually use the findFirstTargetParentComponent()
  25550. method to return a parent component that might want to handle it.
  25551. @see invoke
  25552. */
  25553. virtual ApplicationCommandTarget* getNextCommandTarget() = 0;
  25554. /** This must return a complete list of commands that this target can handle.
  25555. Your target should add all the command IDs that it handles to the array that is
  25556. passed-in.
  25557. */
  25558. virtual void getAllCommands (Array <CommandID>& commands) = 0;
  25559. /** This must provide details about one of the commands that this target can perform.
  25560. This will be called with one of the command IDs that the target provided in its
  25561. getAllCommands() methods.
  25562. It should fill-in all appropriate fields of the ApplicationCommandInfo structure with
  25563. suitable information about the command. (The commandID field will already have been filled-in
  25564. by the caller).
  25565. The easiest way to set the info is using the ApplicationCommandInfo::setInfo() method to
  25566. set all the fields at once.
  25567. If the command is currently inactive for some reason, this method must use
  25568. ApplicationCommandInfo::setActive() to make that clear, (or it should set the isDisabled
  25569. bit of the ApplicationCommandInfo::flags field).
  25570. Any default key-presses for the command should be appended to the
  25571. ApplicationCommandInfo::defaultKeypresses field.
  25572. Note that if you change something that affects the status of the commands
  25573. that would be returned by this method (e.g. something that makes some commands
  25574. active or inactive), you should call ApplicationCommandManager::commandStatusChanged()
  25575. to cause the manager to refresh its status.
  25576. */
  25577. virtual void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result) = 0;
  25578. /** This must actually perform the specified command.
  25579. If this target is able to perform the command specified by the commandID field of the
  25580. InvocationInfo structure, then it should do so, and must return true.
  25581. If it can't handle this command, it should return false, which tells the caller to pass
  25582. the command on to the next target in line.
  25583. @see invoke, ApplicationCommandManager::invoke
  25584. */
  25585. virtual bool perform (const InvocationInfo& info) = 0;
  25586. /** Makes this target invoke a command.
  25587. Your code can call this method to invoke a command on this target, but normally
  25588. you'd call it indirectly via ApplicationCommandManager::invoke() or
  25589. ApplicationCommandManager::invokeDirectly().
  25590. If this target can perform the given command, it will call its perform() method to
  25591. do so. If not, then getNextCommandTarget() will be used to determine the next target
  25592. to try, and the command will be passed along to it.
  25593. @param invocationInfo this must be correctly filled-in, describing the context for
  25594. the invocation.
  25595. @param asynchronously if false, the command will be performed before this method returns.
  25596. If true, a message will be posted so that the command will be performed
  25597. later on the message thread, and this method will return immediately.
  25598. @see perform, ApplicationCommandManager::invoke
  25599. */
  25600. bool invoke (const InvocationInfo& invocationInfo,
  25601. const bool asynchronously);
  25602. /** Invokes a given command directly on this target.
  25603. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  25604. structure.
  25605. */
  25606. bool invokeDirectly (const CommandID commandID,
  25607. const bool asynchronously);
  25608. /** Searches this target and all subsequent ones for the first one that can handle
  25609. the specified command.
  25610. This will use getNextCommandTarget() to determine the chain of targets to try
  25611. after this one.
  25612. */
  25613. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID);
  25614. /** Checks whether this command can currently be performed by this target.
  25615. This will return true only if a call to getCommandInfo() doesn't set the
  25616. isDisabled flag to indicate that the command is inactive.
  25617. */
  25618. bool isCommandActive (const CommandID commandID);
  25619. /** If this object is a Component, this method will seach upwards in its current
  25620. UI hierarchy for the next parent component that implements the
  25621. ApplicationCommandTarget class.
  25622. If your target is a Component, this is a very handy method to use in your
  25623. getNextCommandTarget() implementation.
  25624. */
  25625. ApplicationCommandTarget* findFirstTargetParentComponent();
  25626. private:
  25627. // (for async invocation of commands)
  25628. class CommandTargetMessageInvoker : public MessageListener
  25629. {
  25630. public:
  25631. CommandTargetMessageInvoker (ApplicationCommandTarget* owner);
  25632. ~CommandTargetMessageInvoker();
  25633. void handleMessage (const Message& message);
  25634. private:
  25635. ApplicationCommandTarget* const owner;
  25636. JUCE_DECLARE_NON_COPYABLE (CommandTargetMessageInvoker);
  25637. };
  25638. ScopedPointer <CommandTargetMessageInvoker> messageInvoker;
  25639. friend class CommandTargetMessageInvoker;
  25640. bool tryToInvoke (const InvocationInfo& info, bool async);
  25641. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ApplicationCommandTarget);
  25642. };
  25643. #endif // __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  25644. /*** End of inlined file: juce_ApplicationCommandTarget.h ***/
  25645. /*** Start of inlined file: juce_ActionListener.h ***/
  25646. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  25647. #define __JUCE_ACTIONLISTENER_JUCEHEADER__
  25648. /**
  25649. Receives callbacks to indicate that some kind of event has occurred.
  25650. Used by various classes, e.g. buttons when they are pressed, to tell listeners
  25651. about something that's happened.
  25652. @see ActionBroadcaster, ChangeListener
  25653. */
  25654. class JUCE_API ActionListener
  25655. {
  25656. public:
  25657. /** Destructor. */
  25658. virtual ~ActionListener() {}
  25659. /** Overridden by your subclass to receive the callback.
  25660. @param message the string that was specified when the event was triggered
  25661. by a call to ActionBroadcaster::sendActionMessage()
  25662. */
  25663. virtual void actionListenerCallback (const String& message) = 0;
  25664. };
  25665. #endif // __JUCE_ACTIONLISTENER_JUCEHEADER__
  25666. /*** End of inlined file: juce_ActionListener.h ***/
  25667. /**
  25668. An instance of this class is used to specify initialisation and shutdown
  25669. code for the application.
  25670. An application that wants to run in the JUCE framework needs to declare a
  25671. subclass of JUCEApplication and implement its various pure virtual methods.
  25672. It then needs to use the START_JUCE_APPLICATION macro somewhere in a cpp file
  25673. to declare an instance of this class and generate a suitable platform-specific
  25674. main() function.
  25675. e.g. @code
  25676. class MyJUCEApp : public JUCEApplication
  25677. {
  25678. public:
  25679. MyJUCEApp()
  25680. {
  25681. }
  25682. ~MyJUCEApp()
  25683. {
  25684. }
  25685. void initialise (const String& commandLine)
  25686. {
  25687. myMainWindow = new MyApplicationWindow();
  25688. myMainWindow->setBounds (100, 100, 400, 500);
  25689. myMainWindow->setVisible (true);
  25690. }
  25691. void shutdown()
  25692. {
  25693. myMainWindow = 0;
  25694. }
  25695. const String getApplicationName()
  25696. {
  25697. return "Super JUCE-o-matic";
  25698. }
  25699. const String getApplicationVersion()
  25700. {
  25701. return "1.0";
  25702. }
  25703. private:
  25704. ScopedPointer <MyApplicationWindow> myMainWindow;
  25705. };
  25706. // this creates wrapper code to actually launch the app properly.
  25707. START_JUCE_APPLICATION (MyJUCEApp)
  25708. @endcode
  25709. @see MessageManager
  25710. */
  25711. class JUCE_API JUCEApplication : public ApplicationCommandTarget
  25712. {
  25713. protected:
  25714. /** Constructs a JUCE app object.
  25715. If subclasses implement a constructor or destructor, they shouldn't call any
  25716. JUCE code in there - put your startup/shutdown code in initialise() and
  25717. shutdown() instead.
  25718. */
  25719. JUCEApplication();
  25720. public:
  25721. /** Destructor.
  25722. If subclasses implement a constructor or destructor, they shouldn't call any
  25723. JUCE code in there - put your startup/shutdown code in initialise() and
  25724. shutdown() instead.
  25725. */
  25726. virtual ~JUCEApplication();
  25727. /** Returns the global instance of the application object being run. */
  25728. static JUCEApplication* getInstance() noexcept { return appInstance; }
  25729. /** Called when the application starts.
  25730. This will be called once to let the application do whatever initialisation
  25731. it needs, create its windows, etc.
  25732. After the method returns, the normal event-dispatch loop will be run,
  25733. until the quit() method is called, at which point the shutdown()
  25734. method will be called to let the application clear up anything it needs
  25735. to delete.
  25736. If during the initialise() method, the application decides not to start-up
  25737. after all, it can just call the quit() method and the event loop won't be run.
  25738. @param commandLineParameters the line passed in does not include the
  25739. name of the executable, just the parameter list.
  25740. @see shutdown, quit
  25741. */
  25742. virtual void initialise (const String& commandLineParameters) = 0;
  25743. /** Returns true if the application hasn't yet completed its initialise() method
  25744. and entered the main event loop.
  25745. This is handy for things like splash screens to know when the app's up-and-running
  25746. properly.
  25747. */
  25748. bool isInitialising() const noexcept { return stillInitialising; }
  25749. /* Called to allow the application to clear up before exiting.
  25750. After JUCEApplication::quit() has been called, the event-dispatch loop will
  25751. terminate, and this method will get called to allow the app to sort itself
  25752. out.
  25753. Be careful that nothing happens in this method that might rely on messages
  25754. being sent, or any kind of window activity, because the message loop is no
  25755. longer running at this point.
  25756. @see DeletedAtShutdown
  25757. */
  25758. virtual void shutdown() = 0;
  25759. /** Returns the application's name.
  25760. An application must implement this to name itself.
  25761. */
  25762. virtual const String getApplicationName() = 0;
  25763. /** Returns the application's version number.
  25764. */
  25765. virtual const String getApplicationVersion() = 0;
  25766. /** Checks whether multiple instances of the app are allowed.
  25767. If you application class returns true for this, more than one instance is
  25768. permitted to run (except on the Mac where this isn't possible).
  25769. If it's false, the second instance won't start, but it you will still get a
  25770. callback to anotherInstanceStarted() to tell you about this - which
  25771. gives you a chance to react to what the user was trying to do.
  25772. */
  25773. virtual bool moreThanOneInstanceAllowed();
  25774. /** Indicates that the user has tried to start up another instance of the app.
  25775. This will get called even if moreThanOneInstanceAllowed() is false.
  25776. */
  25777. virtual void anotherInstanceStarted (const String& commandLine);
  25778. /** Called when the operating system is trying to close the application.
  25779. The default implementation of this method is to call quit(), but it may
  25780. be overloaded to ignore the request or do some other special behaviour
  25781. instead. For example, you might want to offer the user the chance to save
  25782. their changes before quitting, and give them the chance to cancel.
  25783. If you want to send a quit signal to your app, this is the correct method
  25784. to call, because it means that requests that come from the system get handled
  25785. in the same way as those from your own application code. So e.g. you'd
  25786. call this method from a "quit" item on a menu bar.
  25787. */
  25788. virtual void systemRequestedQuit();
  25789. /** If any unhandled exceptions make it through to the message dispatch loop, this
  25790. callback will be triggered, in case you want to log them or do some other
  25791. type of error-handling.
  25792. If the type of exception is derived from the std::exception class, the pointer
  25793. passed-in will be valid. If the exception is of unknown type, this pointer
  25794. will be null.
  25795. */
  25796. virtual void unhandledException (const std::exception* e,
  25797. const String& sourceFilename,
  25798. int lineNumber);
  25799. /** Signals that the main message loop should stop and the application should terminate.
  25800. This isn't synchronous, it just posts a quit message to the main queue, and
  25801. when this message arrives, the message loop will stop, the shutdown() method
  25802. will be called, and the app will exit.
  25803. Note that this will cause an unconditional quit to happen, so if you need an
  25804. extra level before this, e.g. to give the user the chance to save their work
  25805. and maybe cancel the quit, you'll need to handle this in the systemRequestedQuit()
  25806. method - see that method's help for more info.
  25807. @see MessageManager
  25808. */
  25809. static void quit();
  25810. /** Sets the value that should be returned as the application's exit code when the
  25811. app quits.
  25812. This is the value that's returned by the main() function. Normally you'd leave this
  25813. as 0 unless you want to indicate an error code.
  25814. @see getApplicationReturnValue
  25815. */
  25816. void setApplicationReturnValue (int newReturnValue) noexcept;
  25817. /** Returns the value that has been set as the application's exit code.
  25818. @see setApplicationReturnValue
  25819. */
  25820. int getApplicationReturnValue() const noexcept { return appReturnValue; }
  25821. /** Returns the application's command line parameters. */
  25822. const String& getCommandLineParameters() const noexcept { return commandLineParameters; }
  25823. /** Returns true if this executable is running as an app (as opposed to being a plugin
  25824. or other kind of shared library. */
  25825. static inline bool isStandaloneApp() noexcept { return createInstance != 0; }
  25826. /** @internal */
  25827. ApplicationCommandTarget* getNextCommandTarget();
  25828. /** @internal */
  25829. void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result);
  25830. /** @internal */
  25831. void getAllCommands (Array <CommandID>& commands);
  25832. /** @internal */
  25833. bool perform (const InvocationInfo& info);
  25834. #ifndef DOXYGEN
  25835. // The following methods are internal calls - not for public use.
  25836. static int main (const String& commandLine);
  25837. static int main (int argc, const char* argv[]);
  25838. static void sendUnhandledException (const std::exception* e, const char* sourceFile, int lineNumber);
  25839. bool initialiseApp (const String& commandLine);
  25840. int shutdownApp();
  25841. static void appWillTerminateByForce();
  25842. typedef JUCEApplication* (*CreateInstanceFunction)();
  25843. static CreateInstanceFunction createInstance;
  25844. #endif
  25845. private:
  25846. static JUCEApplication* appInstance;
  25847. String commandLineParameters;
  25848. ScopedPointer<InterProcessLock> appLock;
  25849. ScopedPointer<ActionListener> broadcastCallback;
  25850. int appReturnValue;
  25851. bool stillInitialising;
  25852. JUCE_DECLARE_NON_COPYABLE (JUCEApplication);
  25853. };
  25854. #endif // __JUCE_APPLICATION_JUCEHEADER__
  25855. /*** End of inlined file: juce_Application.h ***/
  25856. #endif
  25857. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  25858. #endif
  25859. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  25860. #endif
  25861. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  25862. /*** Start of inlined file: juce_ApplicationCommandManager.h ***/
  25863. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  25864. #define __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  25865. /*** Start of inlined file: juce_Desktop.h ***/
  25866. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  25867. #define __JUCE_DESKTOP_JUCEHEADER__
  25868. /*** Start of inlined file: juce_Timer.h ***/
  25869. #ifndef __JUCE_TIMER_JUCEHEADER__
  25870. #define __JUCE_TIMER_JUCEHEADER__
  25871. class InternalTimerThread;
  25872. /**
  25873. Makes repeated callbacks to a virtual method at a specified time interval.
  25874. A Timer's timerCallback() method will be repeatedly called at a given
  25875. interval. When you create a Timer object, it will do nothing until the
  25876. startTimer() method is called, which will cause the message thread to
  25877. start making callbacks at the specified interval, until stopTimer() is called
  25878. or the object is deleted.
  25879. The time interval isn't guaranteed to be precise to any more than maybe
  25880. 10-20ms, and the intervals may end up being much longer than requested if the
  25881. system is busy. Because the callbacks are made by the main message thread,
  25882. anything that blocks the message queue for a period of time will also prevent
  25883. any timers from running until it can carry on.
  25884. If you need to have a single callback that is shared by multiple timers with
  25885. different frequencies, then the MultiTimer class allows you to do that - its
  25886. structure is very similar to the Timer class, but contains multiple timers
  25887. internally, each one identified by an ID number.
  25888. @see MultiTimer
  25889. */
  25890. class JUCE_API Timer
  25891. {
  25892. protected:
  25893. /** Creates a Timer.
  25894. When created, the timer is stopped, so use startTimer() to get it going.
  25895. */
  25896. Timer() noexcept;
  25897. /** Creates a copy of another timer.
  25898. Note that this timer won't be started, even if the one you're copying
  25899. is running.
  25900. */
  25901. Timer (const Timer& other) noexcept;
  25902. public:
  25903. /** Destructor. */
  25904. virtual ~Timer();
  25905. /** The user-defined callback routine that actually gets called periodically.
  25906. It's perfectly ok to call startTimer() or stopTimer() from within this
  25907. callback to change the subsequent intervals.
  25908. */
  25909. virtual void timerCallback() = 0;
  25910. /** Starts the timer and sets the length of interval required.
  25911. If the timer is already started, this will reset it, so the
  25912. time between calling this method and the next timer callback
  25913. will not be less than the interval length passed in.
  25914. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  25915. rounded up to 1)
  25916. */
  25917. void startTimer (int intervalInMilliseconds) noexcept;
  25918. /** Stops the timer.
  25919. No more callbacks will be made after this method returns.
  25920. If this is called from a different thread, any callbacks that may
  25921. be currently executing may be allowed to finish before the method
  25922. returns.
  25923. */
  25924. void stopTimer() noexcept;
  25925. /** Checks if the timer has been started.
  25926. @returns true if the timer is running.
  25927. */
  25928. bool isTimerRunning() const noexcept { return periodMs > 0; }
  25929. /** Returns the timer's interval.
  25930. @returns the timer's interval in milliseconds if it's running, or 0 if it's not.
  25931. */
  25932. int getTimerInterval() const noexcept { return periodMs; }
  25933. private:
  25934. friend class InternalTimerThread;
  25935. int countdownMs, periodMs;
  25936. Timer* previous;
  25937. Timer* next;
  25938. Timer& operator= (const Timer&);
  25939. };
  25940. #endif // __JUCE_TIMER_JUCEHEADER__
  25941. /*** End of inlined file: juce_Timer.h ***/
  25942. /*** Start of inlined file: juce_ComponentAnimator.h ***/
  25943. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  25944. #define __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  25945. /**
  25946. Animates a set of components, moving them to a new position and/or fading their
  25947. alpha levels.
  25948. To animate a component, create a ComponentAnimator instance or (preferably) use the
  25949. global animator object provided by Desktop::getAnimator(), and call its animateComponent()
  25950. method to commence the movement.
  25951. If you're using your own ComponentAnimator instance, you'll need to make sure it isn't
  25952. deleted before it finishes moving the components, or they'll be abandoned before reaching their
  25953. destinations.
  25954. It's ok to delete components while they're being animated - the animator will detect this
  25955. and safely stop using them.
  25956. The class is a ChangeBroadcaster and sends a notification when any components
  25957. start or finish being animated.
  25958. @see Desktop::getAnimator
  25959. */
  25960. class JUCE_API ComponentAnimator : public ChangeBroadcaster,
  25961. private Timer
  25962. {
  25963. public:
  25964. /** Creates a ComponentAnimator. */
  25965. ComponentAnimator();
  25966. /** Destructor. */
  25967. ~ComponentAnimator();
  25968. /** Starts a component moving from its current position to a specified position.
  25969. If the component is already in the middle of an animation, that will be abandoned,
  25970. and a new animation will begin, moving the component from its current location.
  25971. The start and end speed parameters let you apply some acceleration to the component's
  25972. movement.
  25973. @param component the component to move
  25974. @param finalBounds the destination bounds to which the component should move. To leave the
  25975. component in the same place, just pass component->getBounds() for this value
  25976. @param finalAlpha the alpha value that the component should have at the end of the animation
  25977. @param animationDurationMilliseconds how long the animation should last, in milliseconds
  25978. @param useProxyComponent if true, this means the component should be replaced by an internally
  25979. managed temporary component which is a snapshot of the original component.
  25980. This avoids the component having to paint itself as it moves, so may
  25981. be more efficient. This option also allows you to delete the original
  25982. component immediately after starting the animation, because the animation
  25983. can proceed without it. If you use a proxy, the original component will be
  25984. made invisible by this call, and then will become visible again at the end
  25985. of the animation. It'll also mean that the proxy component will be temporarily
  25986. added to the component's parent, so avoid it if this might confuse the parent
  25987. component, or if there's a chance the parent might decide to delete its children.
  25988. @param startSpeed a value to indicate the relative start speed of the animation. If this is 0,
  25989. the component will start by accelerating from rest; higher values mean that it
  25990. will have an initial speed greater than zero. If the value if greater than 1, it
  25991. will decelerate towards the middle of its journey. To move the component at a
  25992. constant rate for its entire animation, set both the start and end speeds to 1.0
  25993. @param endSpeed a relative speed at which the component should be moving when the animation finishes.
  25994. If this is 0, the component will decelerate to a standstill at its final position;
  25995. higher values mean the component will still be moving when it stops. To move the component
  25996. at a constant rate for its entire animation, set both the start and end speeds to 1.0
  25997. */
  25998. void animateComponent (Component* component,
  25999. const Rectangle<int>& finalBounds,
  26000. float finalAlpha,
  26001. int animationDurationMilliseconds,
  26002. bool useProxyComponent,
  26003. double startSpeed,
  26004. double endSpeed);
  26005. /** Begins a fade-out of this components alpha level.
  26006. This is a quick way of invoking animateComponent() with a target alpha value of 0.0f, using
  26007. a proxy. You're safe to delete the component after calling this method, and this won't
  26008. interfere with the animation's progress.
  26009. */
  26010. void fadeOut (Component* component, int millisecondsToTake);
  26011. /** Begins a fade-in of a component.
  26012. This is a quick way of invoking animateComponent() with a target alpha value of 1.0f.
  26013. */
  26014. void fadeIn (Component* component, int millisecondsToTake);
  26015. /** Stops a component if it's currently being animated.
  26016. If moveComponentToItsFinalPosition is true, then the component will
  26017. be immediately moved to its destination position and size. If false, it will be
  26018. left in whatever location it currently occupies.
  26019. */
  26020. void cancelAnimation (Component* component,
  26021. bool moveComponentToItsFinalPosition);
  26022. /** Clears all of the active animations.
  26023. If moveComponentsToTheirFinalPositions is true, all the components will
  26024. be immediately set to their final positions. If false, they will be
  26025. left in whatever locations they currently occupy.
  26026. */
  26027. void cancelAllAnimations (bool moveComponentsToTheirFinalPositions);
  26028. /** Returns the destination position for a component.
  26029. If the component is being animated, this will return the target position that
  26030. was specified when animateComponent() was called.
  26031. If the specified component isn't currently being animated, this method will just
  26032. return its current position.
  26033. */
  26034. const Rectangle<int> getComponentDestination (Component* component);
  26035. /** Returns true if the specified component is currently being animated. */
  26036. bool isAnimating (Component* component) const;
  26037. private:
  26038. class AnimationTask;
  26039. OwnedArray <AnimationTask> tasks;
  26040. uint32 lastTime;
  26041. AnimationTask* findTaskFor (Component* component) const;
  26042. void timerCallback();
  26043. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentAnimator);
  26044. };
  26045. #endif // __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  26046. /*** End of inlined file: juce_ComponentAnimator.h ***/
  26047. class MouseInputSource;
  26048. class MouseInputSourceInternal;
  26049. class MouseListener;
  26050. /**
  26051. Classes can implement this interface and register themselves with the Desktop class
  26052. to receive callbacks when the currently focused component changes.
  26053. @see Desktop::addFocusChangeListener, Desktop::removeFocusChangeListener
  26054. */
  26055. class JUCE_API FocusChangeListener
  26056. {
  26057. public:
  26058. /** Destructor. */
  26059. virtual ~FocusChangeListener() {}
  26060. /** Callback to indicate that the currently focused component has changed. */
  26061. virtual void globalFocusChanged (Component* focusedComponent) = 0;
  26062. };
  26063. /**
  26064. Describes and controls aspects of the computer's desktop.
  26065. */
  26066. class JUCE_API Desktop : private DeletedAtShutdown,
  26067. private Timer,
  26068. private AsyncUpdater
  26069. {
  26070. public:
  26071. /** There's only one dektop object, and this method will return it.
  26072. */
  26073. static Desktop& JUCE_CALLTYPE getInstance();
  26074. /** Returns a list of the positions of all the monitors available.
  26075. The first rectangle in the list will be the main monitor area.
  26076. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  26077. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  26078. */
  26079. const RectangleList getAllMonitorDisplayAreas (bool clippedToWorkArea = true) const;
  26080. /** Returns the position and size of the main monitor.
  26081. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  26082. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  26083. */
  26084. const Rectangle<int> getMainMonitorArea (bool clippedToWorkArea = true) const noexcept;
  26085. /** Returns the position and size of the monitor which contains this co-ordinate.
  26086. If none of the monitors contains the point, this will just return the
  26087. main monitor.
  26088. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  26089. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  26090. */
  26091. const Rectangle<int> getMonitorAreaContaining (const Point<int>& position, bool clippedToWorkArea = true) const;
  26092. /** Returns the mouse position.
  26093. The co-ordinates are relative to the top-left of the main monitor.
  26094. Note that this is just a shortcut for calling getMainMouseSource().getScreenPosition(), and
  26095. you should only resort to grabbing the global mouse position if there's really no
  26096. way to get the coordinates via a mouse event callback instead.
  26097. */
  26098. static const Point<int> getMousePosition();
  26099. /** Makes the mouse pointer jump to a given location.
  26100. The co-ordinates are relative to the top-left of the main monitor.
  26101. */
  26102. static void setMousePosition (const Point<int>& newPosition);
  26103. /** Returns the last position at which a mouse button was pressed.
  26104. Note that this is just a shortcut for calling getMainMouseSource().getLastMouseDownPosition(),
  26105. and in a multi-touch environment, it doesn't make much sense. ALWAYS prefer to
  26106. get this information via other means, such as MouseEvent::getMouseDownScreenPosition()
  26107. if possible, and only ever call this as a last resort.
  26108. */
  26109. static const Point<int> getLastMouseDownPosition();
  26110. /** Returns the number of times the mouse button has been clicked since the
  26111. app started.
  26112. Each mouse-down event increments this number by 1.
  26113. */
  26114. static int getMouseButtonClickCounter();
  26115. /** This lets you prevent the screensaver from becoming active.
  26116. Handy if you're running some sort of presentation app where having a screensaver
  26117. appear would be annoying.
  26118. Pass false to disable the screensaver, and true to re-enable it. (Note that this
  26119. won't enable a screensaver unless the user has actually set one up).
  26120. The disablement will only happen while the Juce application is the foreground
  26121. process - if another task is running in front of it, then the screensaver will
  26122. be unaffected.
  26123. @see isScreenSaverEnabled
  26124. */
  26125. static void setScreenSaverEnabled (bool isEnabled);
  26126. /** Returns true if the screensaver has not been turned off.
  26127. This will return the last value passed into setScreenSaverEnabled(). Note that
  26128. it won't tell you whether the user is actually using a screen saver, just
  26129. whether this app is deliberately preventing one from running.
  26130. @see setScreenSaverEnabled
  26131. */
  26132. static bool isScreenSaverEnabled();
  26133. /** Registers a MouseListener that will receive all mouse events that occur on
  26134. any component.
  26135. @see removeGlobalMouseListener
  26136. */
  26137. void addGlobalMouseListener (MouseListener* listener);
  26138. /** Unregisters a MouseListener that was added with the addGlobalMouseListener()
  26139. method.
  26140. @see addGlobalMouseListener
  26141. */
  26142. void removeGlobalMouseListener (MouseListener* listener);
  26143. /** Registers a MouseListener that will receive a callback whenever the focused
  26144. component changes.
  26145. */
  26146. void addFocusChangeListener (FocusChangeListener* listener);
  26147. /** Unregisters a listener that was added with addFocusChangeListener(). */
  26148. void removeFocusChangeListener (FocusChangeListener* listener);
  26149. /** Takes a component and makes it full-screen, removing the taskbar, dock, etc.
  26150. The component must already be on the desktop for this method to work. It will
  26151. be resized to completely fill the screen and any extraneous taskbars, menu bars,
  26152. etc will be hidden.
  26153. To exit kiosk mode, just call setKioskModeComponent (nullptr). When this is called,
  26154. the component that's currently being used will be resized back to the size
  26155. and position it was in before being put into this mode.
  26156. If allowMenusAndBars is true, things like the menu and dock (on mac) are still
  26157. allowed to pop up when the mouse moves onto them. If this is false, it'll try
  26158. to hide as much on-screen paraphenalia as possible.
  26159. */
  26160. void setKioskModeComponent (Component* componentToUse,
  26161. bool allowMenusAndBars = true);
  26162. /** Returns the component that is currently being used in kiosk-mode.
  26163. This is the component that was last set by setKioskModeComponent(). If none
  26164. has been set, this returns 0.
  26165. */
  26166. Component* getKioskModeComponent() const noexcept { return kioskModeComponent; }
  26167. /** Returns the number of components that are currently active as top-level
  26168. desktop windows.
  26169. @see getComponent, Component::addToDesktop
  26170. */
  26171. int getNumComponents() const noexcept;
  26172. /** Returns one of the top-level desktop window components.
  26173. The index is from 0 to getNumComponents() - 1. This could return 0 if the
  26174. index is out-of-range.
  26175. @see getNumComponents, Component::addToDesktop
  26176. */
  26177. Component* getComponent (int index) const noexcept;
  26178. /** Finds the component at a given screen location.
  26179. This will drill down into top-level windows to find the child component at
  26180. the given position.
  26181. Returns 0 if the co-ordinates are inside a non-Juce window.
  26182. */
  26183. Component* findComponentAt (const Point<int>& screenPosition) const;
  26184. /** The Desktop object has a ComponentAnimator instance which can be used for performing
  26185. your animations.
  26186. Having a single shared ComponentAnimator object makes it more efficient when multiple
  26187. components are being moved around simultaneously. It's also more convenient than having
  26188. to manage your own instance of one.
  26189. @see ComponentAnimator
  26190. */
  26191. ComponentAnimator& getAnimator() noexcept { return animator; }
  26192. /** Returns the current default look-and-feel for components which don't have one
  26193. explicitly set.
  26194. @see setDefaultLookAndFeel
  26195. */
  26196. LookAndFeel& getDefaultLookAndFeel() noexcept;
  26197. /** Changes the default look-and-feel.
  26198. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  26199. set to nullptr, it will revert to using the system's
  26200. default one. The object passed-in must be deleted by the
  26201. caller when it's no longer needed.
  26202. @see getDefaultLookAndFeel
  26203. */
  26204. void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel);
  26205. /** Returns the number of MouseInputSource objects the system has at its disposal.
  26206. In a traditional single-mouse system, there might be only one object. On a multi-touch
  26207. system, there could be one input source per potential finger.
  26208. To find out how many mouse events are currently happening, use getNumDraggingMouseSources().
  26209. @see getMouseSource
  26210. */
  26211. int getNumMouseSources() const noexcept { return mouseSources.size(); }
  26212. /** Returns one of the system's MouseInputSource objects.
  26213. The index should be from 0 to getNumMouseSources() - 1. Out-of-range indexes will return
  26214. a null pointer.
  26215. In a traditional single-mouse system, there might be only one object. On a multi-touch
  26216. system, there could be one input source per potential finger.
  26217. */
  26218. MouseInputSource* getMouseSource (int index) const noexcept { return mouseSources [index]; }
  26219. /** Returns the main mouse input device that the system is using.
  26220. @see getNumMouseSources()
  26221. */
  26222. MouseInputSource& getMainMouseSource() const noexcept { return *mouseSources.getUnchecked(0); }
  26223. /** Returns the number of mouse-sources that are currently being dragged.
  26224. In a traditional single-mouse system, this will be 0 or 1, depending on whether a
  26225. juce component has the button down on it. In a multi-touch system, this could
  26226. be any number from 0 to the number of simultaneous touches that can be detected.
  26227. */
  26228. int getNumDraggingMouseSources() const noexcept;
  26229. /** Returns one of the mouse sources that's currently being dragged.
  26230. The index should be between 0 and getNumDraggingMouseSources() - 1. If the index is
  26231. out of range, or if no mice or fingers are down, this will return a null pointer.
  26232. */
  26233. MouseInputSource* getDraggingMouseSource (int index) const noexcept;
  26234. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  26235. current mouse-drag operation.
  26236. This allows you to make sure that mouseDrag() events are sent continuously, even
  26237. when the mouse isn't moving. This can be useful for things like auto-scrolling
  26238. components when the mouse is near an edge.
  26239. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  26240. minimum interval between consecutive mouse drag callbacks. The callbacks
  26241. will continue until the mouse is released, and then the interval will be reset,
  26242. so you need to make sure it's called every time you begin a drag event.
  26243. Passing an interval of 0 or less will cancel the auto-repeat.
  26244. @see mouseDrag
  26245. */
  26246. void beginDragAutoRepeat (int millisecondsBetweenCallbacks);
  26247. /** In a tablet device which can be turned around, this is used to inidicate the orientation. */
  26248. enum DisplayOrientation
  26249. {
  26250. upright = 1, /**< Indicates that the display is the normal way up. */
  26251. upsideDown = 2, /**< Indicates that the display is upside-down. */
  26252. rotatedClockwise = 4, /**< Indicates that the display is turned 90 degrees clockwise from its upright position. */
  26253. rotatedAntiClockwise = 8, /**< Indicates that the display is turned 90 degrees anti-clockwise from its upright position. */
  26254. allOrientations = 1 + 2 + 4 + 8 /**< A combination of all the orientation values */
  26255. };
  26256. /** In a tablet device which can be turned around, this returns the current orientation. */
  26257. DisplayOrientation getCurrentOrientation() const;
  26258. /** Sets which orientations the display is allowed to auto-rotate to.
  26259. For devices that support rotating desktops, this lets you specify which of the orientations your app can use.
  26260. The parameter is a bitwise or-ed combination of the values in DisplayOrientation, and must contain at least one
  26261. set bit.
  26262. */
  26263. void setOrientationsEnabled (int allowedOrientations);
  26264. /** Returns whether the display is allowed to auto-rotate to the given orientation.
  26265. Each orientation can be enabled using setOrientationEnabled(). By default, all orientations are allowed.
  26266. */
  26267. bool isOrientationEnabled (DisplayOrientation orientation) const noexcept;
  26268. /** Tells this object to refresh its idea of what the screen resolution is.
  26269. (Called internally by the native code).
  26270. */
  26271. void refreshMonitorSizes();
  26272. /** True if the OS supports semitransparent windows */
  26273. static bool canUseSemiTransparentWindows() noexcept;
  26274. private:
  26275. static Desktop* instance;
  26276. friend class Component;
  26277. friend class ComponentPeer;
  26278. friend class MouseInputSource;
  26279. friend class MouseInputSourceInternal;
  26280. friend class DeletedAtShutdown;
  26281. friend class TopLevelWindowManager;
  26282. OwnedArray <MouseInputSource> mouseSources;
  26283. void createMouseInputSources();
  26284. ListenerList <MouseListener> mouseListeners;
  26285. ListenerList <FocusChangeListener> focusListeners;
  26286. Array <Component*> desktopComponents;
  26287. Array <Rectangle<int> > monitorCoordsClipped, monitorCoordsUnclipped;
  26288. Point<int> lastFakeMouseMove;
  26289. void sendMouseMove();
  26290. int mouseClickCounter;
  26291. void incrementMouseClickCounter() noexcept;
  26292. ScopedPointer<Timer> dragRepeater;
  26293. ScopedPointer<LookAndFeel> defaultLookAndFeel;
  26294. WeakReference<LookAndFeel> currentLookAndFeel;
  26295. Component* kioskModeComponent;
  26296. Rectangle<int> kioskComponentOriginalBounds;
  26297. int allowedOrientations;
  26298. ComponentAnimator animator;
  26299. void timerCallback();
  26300. void resetTimer();
  26301. int getNumDisplayMonitors() const noexcept;
  26302. const Rectangle<int> getDisplayMonitorCoordinates (int index, bool clippedToWorkArea) const noexcept;
  26303. static void getCurrentMonitorPositions (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea);
  26304. void addDesktopComponent (Component* c);
  26305. void removeDesktopComponent (Component* c);
  26306. void componentBroughtToFront (Component* c);
  26307. static void setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  26308. void triggerFocusCallback();
  26309. void handleAsyncUpdate();
  26310. Desktop();
  26311. ~Desktop();
  26312. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Desktop);
  26313. };
  26314. #endif // __JUCE_DESKTOP_JUCEHEADER__
  26315. /*** End of inlined file: juce_Desktop.h ***/
  26316. class KeyPressMappingSet;
  26317. class ApplicationCommandManagerListener;
  26318. /**
  26319. One of these objects holds a list of all the commands your app can perform,
  26320. and despatches these commands when needed.
  26321. Application commands are a good way to trigger actions in your app, e.g. "Quit",
  26322. "Copy", "Paste", etc. Menus, buttons and keypresses can all be given commands
  26323. to invoke automatically, which means you don't have to handle the result of a menu
  26324. or button click manually. Commands are despatched to ApplicationCommandTarget objects
  26325. which can choose which events they want to handle.
  26326. This architecture also allows for nested ApplicationCommandTargets, so that for example
  26327. you could have two different objects, one inside the other, both of which can respond to
  26328. a "delete" command. Depending on which one has focus, the command will be sent to the
  26329. appropriate place, regardless of whether it was triggered by a menu, keypress or some other
  26330. method.
  26331. To set up your app to use commands, you'll need to do the following:
  26332. - Create a global ApplicationCommandManager to hold the list of all possible
  26333. commands. (This will also manage a set of key-mappings for them).
  26334. - Make some of your UI components (or other objects) inherit from ApplicationCommandTarget.
  26335. This allows the object to provide a list of commands that it can perform, and
  26336. to handle them.
  26337. - Register each type of command using ApplicationCommandManager::registerAllCommandsForTarget(),
  26338. or ApplicationCommandManager::registerCommand().
  26339. - If you want key-presses to trigger your commands, use the ApplicationCommandManager::getKeyMappings()
  26340. method to access the key-mapper object, which you will need to register as a key-listener
  26341. in whatever top-level component you're using. See the KeyPressMappingSet class for more help
  26342. about setting this up.
  26343. - Use methods such as PopupMenu::addCommandItem() or Button::setCommandToTrigger() to
  26344. cause these commands to be invoked automatically.
  26345. - Commands can be invoked directly by your code using ApplicationCommandManager::invokeDirectly().
  26346. When a command is invoked, the ApplicationCommandManager will try to choose the best
  26347. ApplicationCommandTarget to receive the specified command. To do this it will use the
  26348. current keyboard focus to see which component might be interested, and will search the
  26349. component hierarchy for those that also implement the ApplicationCommandTarget interface.
  26350. If an ApplicationCommandTarget isn't interested in the command that is being invoked, then
  26351. the next one in line will be tried (see the ApplicationCommandTarget::getNextCommandTarget()
  26352. method), and so on until ApplicationCommandTarget::getNextCommandTarget() returns 0. At this
  26353. point if the command still hasn't been performed, it will be passed to the current
  26354. JUCEApplication object (which is itself an ApplicationCommandTarget).
  26355. To exert some custom control over which ApplicationCommandTarget is chosen to invoke a command,
  26356. you can override the ApplicationCommandManager::getFirstCommandTarget() method and choose
  26357. the object yourself.
  26358. @see ApplicationCommandTarget, ApplicationCommandInfo
  26359. */
  26360. class JUCE_API ApplicationCommandManager : private AsyncUpdater,
  26361. private FocusChangeListener
  26362. {
  26363. public:
  26364. /** Creates an ApplicationCommandManager.
  26365. Once created, you'll need to register all your app's commands with it, using
  26366. ApplicationCommandManager::registerAllCommandsForTarget() or
  26367. ApplicationCommandManager::registerCommand().
  26368. */
  26369. ApplicationCommandManager();
  26370. /** Destructor.
  26371. Make sure that you don't delete this if pointers to it are still being used by
  26372. objects such as PopupMenus or Buttons.
  26373. */
  26374. virtual ~ApplicationCommandManager();
  26375. /** Clears the current list of all commands.
  26376. Note that this will also clear the contents of the KeyPressMappingSet.
  26377. */
  26378. void clearCommands();
  26379. /** Adds a command to the list of registered commands.
  26380. @see registerAllCommandsForTarget
  26381. */
  26382. void registerCommand (const ApplicationCommandInfo& newCommand);
  26383. /** Adds all the commands that this target publishes to the manager's list.
  26384. This will use ApplicationCommandTarget::getAllCommands() and ApplicationCommandTarget::getCommandInfo()
  26385. to get details about all the commands that this target can do, and will call
  26386. registerCommand() to add each one to the manger's list.
  26387. @see registerCommand
  26388. */
  26389. void registerAllCommandsForTarget (ApplicationCommandTarget* target);
  26390. /** Removes the command with a specified ID.
  26391. Note that this will also remove any key mappings that are mapped to the command.
  26392. */
  26393. void removeCommand (CommandID commandID);
  26394. /** This should be called to tell the manager that one of its registered commands may have changed
  26395. its active status.
  26396. Because the command manager only finds out whether a command is active or inactive by querying
  26397. the current ApplicationCommandTarget, this is used to tell it that things may have changed. It
  26398. allows things like buttons to update their enablement, etc.
  26399. This method will cause an asynchronous call to ApplicationCommandManagerListener::applicationCommandListChanged()
  26400. for any registered listeners.
  26401. */
  26402. void commandStatusChanged();
  26403. /** Returns the number of commands that have been registered.
  26404. @see registerCommand
  26405. */
  26406. int getNumCommands() const noexcept { return commands.size(); }
  26407. /** Returns the details about one of the registered commands.
  26408. The index is between 0 and (getNumCommands() - 1).
  26409. */
  26410. const ApplicationCommandInfo* getCommandForIndex (int index) const noexcept { return commands [index]; }
  26411. /** Returns the details about a given command ID.
  26412. This will search the list of registered commands for one with the given command
  26413. ID number, and return its associated info. If no matching command is found, this
  26414. will return 0.
  26415. */
  26416. const ApplicationCommandInfo* getCommandForID (CommandID commandID) const noexcept;
  26417. /** Returns the name field for a command.
  26418. An empty string is returned if no command with this ID has been registered.
  26419. @see getDescriptionOfCommand
  26420. */
  26421. String getNameOfCommand (CommandID commandID) const noexcept;
  26422. /** Returns the description field for a command.
  26423. An empty string is returned if no command with this ID has been registered. If the
  26424. command has no description, this will return its short name field instead.
  26425. @see getNameOfCommand
  26426. */
  26427. String getDescriptionOfCommand (CommandID commandID) const noexcept;
  26428. /** Returns the list of categories.
  26429. This will go through all registered commands, and return a list of all the distict
  26430. categoryName values from their ApplicationCommandInfo structure.
  26431. @see getCommandsInCategory()
  26432. */
  26433. StringArray getCommandCategories() const;
  26434. /** Returns a list of all the command UIDs in a particular category.
  26435. @see getCommandCategories()
  26436. */
  26437. Array<CommandID> getCommandsInCategory (const String& categoryName) const;
  26438. /** Returns the manager's internal set of key mappings.
  26439. This object can be used to edit the keypresses. To actually link this object up
  26440. to invoke commands when a key is pressed, see the comments for the KeyPressMappingSet
  26441. class.
  26442. @see KeyPressMappingSet
  26443. */
  26444. KeyPressMappingSet* getKeyMappings() const noexcept { return keyMappings; }
  26445. /** Invokes the given command directly, sending it to the default target.
  26446. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  26447. structure.
  26448. */
  26449. bool invokeDirectly (CommandID commandID, bool asynchronously);
  26450. /** Sends a command to the default target.
  26451. This will choose a target using getFirstCommandTarget(), and send the specified command
  26452. to it using the ApplicationCommandTarget::invoke() method. This means that if the
  26453. first target can't handle the command, it will be passed on to targets further down the
  26454. chain (see ApplicationCommandTarget::invoke() for more info).
  26455. @param invocationInfo this must be correctly filled-in, describing the context for
  26456. the invocation.
  26457. @param asynchronously if false, the command will be performed before this method returns.
  26458. If true, a message will be posted so that the command will be performed
  26459. later on the message thread, and this method will return immediately.
  26460. @see ApplicationCommandTarget::invoke
  26461. */
  26462. bool invoke (const ApplicationCommandTarget::InvocationInfo& invocationInfo,
  26463. bool asynchronously);
  26464. /** Chooses the ApplicationCommandTarget to which a command should be sent.
  26465. Whenever the manager needs to know which target a command should be sent to, it calls
  26466. this method to determine the first one to try.
  26467. By default, this method will return the target that was set by calling setFirstCommandTarget().
  26468. If no target is set, it will return the result of findDefaultComponentTarget().
  26469. If you need to make sure all commands go via your own custom target, then you can
  26470. either use setFirstCommandTarget() to specify a single target, or override this method
  26471. if you need more complex logic to choose one.
  26472. It may return 0 if no targets are available.
  26473. @see getTargetForCommand, invoke, invokeDirectly
  26474. */
  26475. virtual ApplicationCommandTarget* getFirstCommandTarget (CommandID commandID);
  26476. /** Sets a target to be returned by getFirstCommandTarget().
  26477. If this is set to 0, then getFirstCommandTarget() will by default return the
  26478. result of findDefaultComponentTarget().
  26479. If you use this to set a target, make sure you call setFirstCommandTarget (0) before
  26480. deleting the target object.
  26481. */
  26482. void setFirstCommandTarget (ApplicationCommandTarget* newTarget) noexcept;
  26483. /** Tries to find the best target to use to perform a given command.
  26484. This will call getFirstCommandTarget() to find the preferred target, and will
  26485. check whether that target can handle the given command. If it can't, then it'll use
  26486. ApplicationCommandTarget::getNextCommandTarget() to find the next one to try, and
  26487. so on until no more are available.
  26488. If no targets are found that can perform the command, this method will return 0.
  26489. If a target is found, then it will get the target to fill-in the upToDateInfo
  26490. structure with the latest info about that command, so that the caller can see
  26491. whether the command is disabled, ticked, etc.
  26492. */
  26493. ApplicationCommandTarget* getTargetForCommand (CommandID commandID,
  26494. ApplicationCommandInfo& upToDateInfo);
  26495. /** Registers a listener that will be called when various events occur. */
  26496. void addListener (ApplicationCommandManagerListener* listener);
  26497. /** Deregisters a previously-added listener. */
  26498. void removeListener (ApplicationCommandManagerListener* listener);
  26499. /** Looks for a suitable command target based on which Components have the keyboard focus.
  26500. This is used by the default implementation of ApplicationCommandTarget::getFirstCommandTarget(),
  26501. but is exposed here in case it's useful.
  26502. It tries to pick the best ApplicationCommandTarget by looking at focused components, top level
  26503. windows, etc., and using the findTargetForComponent() method.
  26504. */
  26505. static ApplicationCommandTarget* findDefaultComponentTarget();
  26506. /** Examines this component and all its parents in turn, looking for the first one
  26507. which is a ApplicationCommandTarget.
  26508. Returns the first ApplicationCommandTarget that it finds, or 0 if none of them implement
  26509. that class.
  26510. */
  26511. static ApplicationCommandTarget* findTargetForComponent (Component* component);
  26512. private:
  26513. OwnedArray <ApplicationCommandInfo> commands;
  26514. ListenerList <ApplicationCommandManagerListener> listeners;
  26515. ScopedPointer <KeyPressMappingSet> keyMappings;
  26516. ApplicationCommandTarget* firstTarget;
  26517. void sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info);
  26518. void handleAsyncUpdate();
  26519. void globalFocusChanged (Component*);
  26520. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  26521. // This is just here to cause a compile error in old code that hasn't been changed to use the new
  26522. // version of this method.
  26523. virtual short getFirstCommandTarget() { return 0; }
  26524. #endif
  26525. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ApplicationCommandManager);
  26526. };
  26527. /**
  26528. A listener that receives callbacks from an ApplicationCommandManager when
  26529. commands are invoked or the command list is changed.
  26530. @see ApplicationCommandManager::addListener, ApplicationCommandManager::removeListener
  26531. */
  26532. class JUCE_API ApplicationCommandManagerListener
  26533. {
  26534. public:
  26535. /** Destructor. */
  26536. virtual ~ApplicationCommandManagerListener() {}
  26537. /** Called when an app command is about to be invoked. */
  26538. virtual void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info) = 0;
  26539. /** Called when commands are registered or deregistered from the
  26540. command manager, or when commands are made active or inactive.
  26541. Note that if you're using this to watch for changes to whether a command is disabled,
  26542. you'll need to make sure that ApplicationCommandManager::commandStatusChanged() is called
  26543. whenever the status of your command might have changed.
  26544. */
  26545. virtual void applicationCommandListChanged() = 0;
  26546. };
  26547. #endif // __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  26548. /*** End of inlined file: juce_ApplicationCommandManager.h ***/
  26549. #endif
  26550. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  26551. #endif
  26552. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  26553. /*** Start of inlined file: juce_ApplicationProperties.h ***/
  26554. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  26555. #define __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  26556. /*** Start of inlined file: juce_PropertiesFile.h ***/
  26557. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  26558. #define __JUCE_PROPERTIESFILE_JUCEHEADER__
  26559. /** Wrapper on a file that stores a list of key/value data pairs.
  26560. Useful for storing application settings, etc. See the PropertySet class for
  26561. the interfaces that read and write values.
  26562. Not designed for very large amounts of data, as it keeps all the values in
  26563. memory and writes them out to disk lazily when they are changed.
  26564. Because this class derives from ChangeBroadcaster, ChangeListeners can be registered
  26565. with it, and these will be signalled when a value changes.
  26566. @see PropertySet
  26567. */
  26568. class JUCE_API PropertiesFile : public PropertySet,
  26569. public ChangeBroadcaster,
  26570. private Timer
  26571. {
  26572. public:
  26573. enum StorageFormat
  26574. {
  26575. storeAsBinary,
  26576. storeAsCompressedBinary,
  26577. storeAsXML
  26578. };
  26579. struct Options
  26580. {
  26581. /** Creates an empty Options structure.
  26582. You'll need to fill-in the data memebers appropriately before using this structure.
  26583. */
  26584. Options();
  26585. /** The name of your application - this is used to help generate the path and filename
  26586. at which the properties file will be stored. */
  26587. String applicationName;
  26588. /** The suffix to use for your properties file.
  26589. It doesn't really matter what this is - you may want to use ".settings" or
  26590. ".properties" or something.
  26591. */
  26592. String filenameSuffix;
  26593. /** The name of a subfolder in which you'd like your properties file to live.
  26594. See the getDefaultFile() method for more details about how this is used.
  26595. */
  26596. String folderName;
  26597. /** If you're using properties files on a Mac, you must set this value - failure to
  26598. do so will cause a runtime assertion.
  26599. The PropertiesFile class always used to put its settings files in "Library/Preferences", but Apple
  26600. have changed their advice, and now stipulate that settings should go in "Library/Application Support".
  26601. Because older apps would be broken by a silent change in this class's behaviour, you must now
  26602. explicitly set the osxLibrarySubFolder value to indicate which path you want to use.
  26603. In newer apps, you should always set this to "Application Support".
  26604. If your app needs to load settings files that were created by older versions of juce and
  26605. you want to maintain backwards-compatibility, then you can set this to "Preferences".
  26606. But.. for better Apple-compliance, the recommended approach would be to write some code that
  26607. finds your old settings files in ~/Library/Preferences, moves them to ~/Library/Application Support,
  26608. and then uses the new path.
  26609. */
  26610. String osxLibrarySubFolder;
  26611. /** If true, the file will be created in a location that's shared between users.
  26612. The default constructor initialises this value to false.
  26613. */
  26614. bool commonToAllUsers;
  26615. /** If true, this means that property names are matched in a case-insensitive manner.
  26616. See the PropertySet constructor for more info.
  26617. The default constructor initialises this value to false.
  26618. */
  26619. bool ignoreCaseOfKeyNames;
  26620. /** If this is zero or greater, then after a value is changed, the object will wait
  26621. for this amount of time and then save the file. If this zero, the file will be
  26622. written to disk immediately on being changed (which might be slow, as it'll re-write
  26623. synchronously each time a value-change method is called). If it is less than zero,
  26624. the file won't be saved until save() or saveIfNeeded() are explicitly called.
  26625. The default constructor sets this to a reasonable value of a few seconds, so you
  26626. only need to change it if you need a special case.
  26627. */
  26628. int millisecondsBeforeSaving;
  26629. /** Specifies whether the file should be written as XML, binary, etc.
  26630. The default constructor sets this to storeAsXML, so you only need to set it explicitly
  26631. if you want to use a different format.
  26632. */
  26633. StorageFormat storageFormat;
  26634. /** An optional InterprocessLock object that will be used to prevent multiple threads or
  26635. processes from writing to the file at the same time. The PropertiesFile will keep a
  26636. pointer to this object but will not take ownership of it - the caller is responsible for
  26637. making sure that the lock doesn't get deleted before the PropertiesFile has been deleted.
  26638. The default constructor initialises this value to nullptr, so you don't need to touch it
  26639. unless you want to use a lock.
  26640. */
  26641. InterProcessLock* processLock;
  26642. /** This can be called to suggest a file that should be used, based on the values
  26643. in this structure.
  26644. So on a Mac, this will return a file called:
  26645. ~/Library/[osxLibrarySubFolder]/[folderName]/[applicationName].[filenameSuffix]
  26646. On Windows it'll return something like:
  26647. C:\\Documents and Settings\\username\\Application Data\\[folderName]\\[applicationName].[filenameSuffix]
  26648. On Linux it'll return
  26649. ~/.[folderName]/[applicationName].[filenameSuffix]
  26650. If the folderName variable is empty, it'll use the app name for this (or omit the
  26651. folder name on the Mac).
  26652. The paths will also vary depending on whether commonToAllUsers is true.
  26653. */
  26654. File getDefaultFile() const;
  26655. };
  26656. /** Creates a PropertiesFile object.
  26657. The file used will be chosen by calling PropertiesFile::Options::getDefaultFile()
  26658. for the options provided. To set the file explicitly, use the other constructor.
  26659. */
  26660. explicit PropertiesFile (const Options& options);
  26661. /** Creates a PropertiesFile object.
  26662. Unlike the other constructor, this one allows you to explicitly set the file that you
  26663. want to be used, rather than using the default one.
  26664. */
  26665. PropertiesFile (const File& file,
  26666. const Options& options);
  26667. /** Destructor.
  26668. When deleted, the file will first call saveIfNeeded() to flush any changes to disk.
  26669. */
  26670. ~PropertiesFile();
  26671. /** Returns true if this file was created from a valid (or non-existent) file.
  26672. If the file failed to load correctly because it was corrupt or had insufficient
  26673. access, this will be false.
  26674. */
  26675. bool isValidFile() const noexcept { return loadedOk; }
  26676. /** This will flush all the values to disk if they've changed since the last
  26677. time they were saved.
  26678. Returns false if it fails to write to the file for some reason (maybe because
  26679. it's read-only or the directory doesn't exist or something).
  26680. @see save
  26681. */
  26682. bool saveIfNeeded();
  26683. /** This will force a write-to-disk of the current values, regardless of whether
  26684. anything has changed since the last save.
  26685. Returns false if it fails to write to the file for some reason (maybe because
  26686. it's read-only or the directory doesn't exist or something).
  26687. @see saveIfNeeded
  26688. */
  26689. bool save();
  26690. /** Returns true if the properties have been altered since the last time they were saved.
  26691. The file is flagged as needing to be saved when you change a value, but you can
  26692. explicitly set this flag with setNeedsToBeSaved().
  26693. */
  26694. bool needsToBeSaved() const;
  26695. /** Explicitly sets the flag to indicate whether the file needs saving or not.
  26696. @see needsToBeSaved
  26697. */
  26698. void setNeedsToBeSaved (bool needsToBeSaved);
  26699. /** Returns the file that's being used. */
  26700. File getFile() const { return file; }
  26701. protected:
  26702. /** @internal */
  26703. virtual void propertyChanged();
  26704. private:
  26705. File file;
  26706. Options options;
  26707. bool loadedOk, needsWriting;
  26708. typedef const ScopedPointer<InterProcessLock::ScopedLockType> ProcessScopedLock;
  26709. InterProcessLock::ScopedLockType* createProcessLock() const;
  26710. void timerCallback();
  26711. void initialise();
  26712. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PropertiesFile);
  26713. };
  26714. #endif // __JUCE_PROPERTIESFILE_JUCEHEADER__
  26715. /*** End of inlined file: juce_PropertiesFile.h ***/
  26716. /**
  26717. Manages a collection of properties.
  26718. This is a slightly higher-level wrapper for PropertiesFile, which can be used
  26719. as a singleton.
  26720. It holds two different PropertiesFile objects internally, one for user-specific
  26721. settings (stored in your user directory), and one for settings that are common to
  26722. all users (stored in a folder accessible to all users).
  26723. The class manages the creation of these files on-demand, allowing access via the
  26724. getUserSettings() and getCommonSettings() methods. It also has a few handy
  26725. methods like testWriteAccess() to check that the files can be saved.
  26726. If you're using one of these as a singleton, then your app's start-up code should
  26727. first of all call setStorageParameters() to tell it the parameters to use to create
  26728. the properties files.
  26729. @see PropertiesFile
  26730. */
  26731. class JUCE_API ApplicationProperties : public DeletedAtShutdown
  26732. {
  26733. public:
  26734. /**
  26735. Creates an ApplicationProperties object.
  26736. Before using it, you must call setStorageParameters() to give it the info
  26737. it needs to create the property files.
  26738. */
  26739. ApplicationProperties();
  26740. /** Destructor. */
  26741. ~ApplicationProperties();
  26742. juce_DeclareSingleton (ApplicationProperties, false);
  26743. /** Gives the object the information it needs to create the appropriate properties files.
  26744. See the PropertiesFile::Options class for details about what options you need to set.
  26745. */
  26746. void setStorageParameters (const PropertiesFile::Options& options);
  26747. /** Tests whether the files can be successfully written to, and can show
  26748. an error message if not.
  26749. Returns true if none of the tests fail.
  26750. @param testUserSettings if true, the user settings file will be tested
  26751. @param testCommonSettings if true, the common settings file will be tested
  26752. @param showWarningDialogOnFailure if true, the method will show a helpful error
  26753. message box if either of the tests fail
  26754. */
  26755. bool testWriteAccess (bool testUserSettings,
  26756. bool testCommonSettings,
  26757. bool showWarningDialogOnFailure);
  26758. /** Returns the user settings file.
  26759. The first time this is called, it will create and load the properties file.
  26760. Note that when you search the user PropertiesFile for a value that it doesn't contain,
  26761. the common settings are used as a second-chance place to look. This is done via the
  26762. PropertySet::setFallbackPropertySet() method - by default the common settings are set
  26763. to the fallback for the user settings.
  26764. @see getCommonSettings
  26765. */
  26766. PropertiesFile* getUserSettings();
  26767. /** Returns the common settings file.
  26768. The first time this is called, it will create and load the properties file.
  26769. @param returnUserPropsIfReadOnly if this is true, and the common properties file is
  26770. read-only (e.g. because the user doesn't have permission to write
  26771. to shared files), then this will return the user settings instead,
  26772. (like getUserSettings() would do). This is handy if you'd like to
  26773. write a value to the common settings, but if that's no possible,
  26774. then you'd rather write to the user settings than none at all.
  26775. If returnUserPropsIfReadOnly is false, this method will always return
  26776. the common settings, even if any changes to them can't be saved.
  26777. @see getUserSettings
  26778. */
  26779. PropertiesFile* getCommonSettings (bool returnUserPropsIfReadOnly);
  26780. /** Saves both files if they need to be saved.
  26781. @see PropertiesFile::saveIfNeeded
  26782. */
  26783. bool saveIfNeeded();
  26784. /** Flushes and closes both files if they are open.
  26785. This flushes any pending changes to disk with PropertiesFile::saveIfNeeded()
  26786. and closes both files. They will then be re-opened the next time getUserSettings()
  26787. or getCommonSettings() is called.
  26788. */
  26789. void closeFiles();
  26790. private:
  26791. PropertiesFile::Options options;
  26792. ScopedPointer <PropertiesFile> userProps, commonProps;
  26793. int commonSettingsAreReadOnly;
  26794. void openFiles();
  26795. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ApplicationProperties);
  26796. };
  26797. #endif // __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  26798. /*** End of inlined file: juce_ApplicationProperties.h ***/
  26799. #endif
  26800. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26801. /*** Start of inlined file: juce_AiffAudioFormat.h ***/
  26802. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26803. #define __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26804. /*** Start of inlined file: juce_AudioFormat.h ***/
  26805. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  26806. #define __JUCE_AUDIOFORMAT_JUCEHEADER__
  26807. /*** Start of inlined file: juce_AudioFormatReader.h ***/
  26808. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  26809. #define __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  26810. /*** Start of inlined file: juce_AudioDataConverters.h ***/
  26811. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  26812. #define __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  26813. /**
  26814. This class a container which holds all the classes pertaining to the AudioData::Pointer
  26815. audio sample format class.
  26816. @see AudioData::Pointer.
  26817. */
  26818. class JUCE_API AudioData
  26819. {
  26820. public:
  26821. // These types can be used as the SampleFormat template parameter for the AudioData::Pointer class.
  26822. class Int8; /**< Used as a template parameter for AudioData::Pointer. Indicates an 8-bit integer packed data format. */
  26823. class UInt8; /**< Used as a template parameter for AudioData::Pointer. Indicates an 8-bit unsigned integer packed data format. */
  26824. class Int16; /**< Used as a template parameter for AudioData::Pointer. Indicates an 16-bit integer packed data format. */
  26825. class Int24; /**< Used as a template parameter for AudioData::Pointer. Indicates an 24-bit integer packed data format. */
  26826. class Int32; /**< Used as a template parameter for AudioData::Pointer. Indicates an 32-bit integer packed data format. */
  26827. class Float32; /**< Used as a template parameter for AudioData::Pointer. Indicates an 32-bit float data format. */
  26828. // These types can be used as the Endianness template parameter for the AudioData::Pointer class.
  26829. class BigEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in big-endian order. */
  26830. class LittleEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in little-endian order. */
  26831. class NativeEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in the CPU's native endianness. */
  26832. // These types can be used as the InterleavingType template parameter for the AudioData::Pointer class.
  26833. class NonInterleaved; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored contiguously. */
  26834. class Interleaved; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are interleaved with a number of other channels. */
  26835. // These types can be used as the Constness template parameter for the AudioData::Pointer class.
  26836. class NonConst; /**< Used as a template parameter for AudioData::Pointer. Indicates that the pointer can be used for non-const data. */
  26837. class Const; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples can only be used for const data.. */
  26838. #ifndef DOXYGEN
  26839. class BigEndian
  26840. {
  26841. public:
  26842. template <class SampleFormatType> static inline float getAsFloat (SampleFormatType& s) noexcept { return s.getAsFloatBE(); }
  26843. template <class SampleFormatType> static inline void setAsFloat (SampleFormatType& s, float newValue) noexcept { s.setAsFloatBE (newValue); }
  26844. template <class SampleFormatType> static inline int32 getAsInt32 (SampleFormatType& s) noexcept { return s.getAsInt32BE(); }
  26845. template <class SampleFormatType> static inline void setAsInt32 (SampleFormatType& s, int32 newValue) noexcept { s.setAsInt32BE (newValue); }
  26846. template <class SourceType, class DestType> static inline void copyFrom (DestType& dest, SourceType& source) noexcept { dest.copyFromBE (source); }
  26847. enum { isBigEndian = 1 };
  26848. };
  26849. class LittleEndian
  26850. {
  26851. public:
  26852. template <class SampleFormatType> static inline float getAsFloat (SampleFormatType& s) noexcept { return s.getAsFloatLE(); }
  26853. template <class SampleFormatType> static inline void setAsFloat (SampleFormatType& s, float newValue) noexcept { s.setAsFloatLE (newValue); }
  26854. template <class SampleFormatType> static inline int32 getAsInt32 (SampleFormatType& s) noexcept { return s.getAsInt32LE(); }
  26855. template <class SampleFormatType> static inline void setAsInt32 (SampleFormatType& s, int32 newValue) noexcept { s.setAsInt32LE (newValue); }
  26856. template <class SourceType, class DestType> static inline void copyFrom (DestType& dest, SourceType& source) noexcept { dest.copyFromLE (source); }
  26857. enum { isBigEndian = 0 };
  26858. };
  26859. #if JUCE_BIG_ENDIAN
  26860. class NativeEndian : public BigEndian {};
  26861. #else
  26862. class NativeEndian : public LittleEndian {};
  26863. #endif
  26864. class Int8
  26865. {
  26866. public:
  26867. inline Int8 (void* data_) noexcept : data (static_cast <int8*> (data_)) {}
  26868. inline void advance() noexcept { ++data; }
  26869. inline void skip (int numSamples) noexcept { data += numSamples; }
  26870. inline float getAsFloatLE() const noexcept { return (float) (*data * (1.0 / (1.0 + maxValue))); }
  26871. inline float getAsFloatBE() const noexcept { return getAsFloatLE(); }
  26872. inline void setAsFloatLE (float newValue) noexcept { *data = (int8) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue))); }
  26873. inline void setAsFloatBE (float newValue) noexcept { setAsFloatLE (newValue); }
  26874. inline int32 getAsInt32LE() const noexcept { return (int) (*data << 24); }
  26875. inline int32 getAsInt32BE() const noexcept { return getAsInt32LE(); }
  26876. inline void setAsInt32LE (int newValue) noexcept { *data = (int8) (newValue >> 24); }
  26877. inline void setAsInt32BE (int newValue) noexcept { setAsInt32LE (newValue); }
  26878. inline void clear() noexcept { *data = 0; }
  26879. inline void clearMultiple (int num) noexcept { zeromem (data, num * bytesPerSample) ;}
  26880. template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsInt32LE (source.getAsInt32()); }
  26881. template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsInt32BE (source.getAsInt32()); }
  26882. inline void copyFromSameType (Int8& source) noexcept { *data = *source.data; }
  26883. int8* data;
  26884. enum { bytesPerSample = 1, maxValue = 0x7f, resolution = (1 << 24), isFloat = 0 };
  26885. };
  26886. class UInt8
  26887. {
  26888. public:
  26889. inline UInt8 (void* data_) noexcept : data (static_cast <uint8*> (data_)) {}
  26890. inline void advance() noexcept { ++data; }
  26891. inline void skip (int numSamples) noexcept { data += numSamples; }
  26892. inline float getAsFloatLE() const noexcept { return (float) ((*data - 128) * (1.0 / (1.0 + maxValue))); }
  26893. inline float getAsFloatBE() const noexcept { return getAsFloatLE(); }
  26894. inline void setAsFloatLE (float newValue) noexcept { *data = (uint8) jlimit (0, 255, 128 + roundToInt (newValue * (1.0 + maxValue))); }
  26895. inline void setAsFloatBE (float newValue) noexcept { setAsFloatLE (newValue); }
  26896. inline int32 getAsInt32LE() const noexcept { return (int) ((*data - 128) << 24); }
  26897. inline int32 getAsInt32BE() const noexcept { return getAsInt32LE(); }
  26898. inline void setAsInt32LE (int newValue) noexcept { *data = (uint8) (128 + (newValue >> 24)); }
  26899. inline void setAsInt32BE (int newValue) noexcept { setAsInt32LE (newValue); }
  26900. inline void clear() noexcept { *data = 128; }
  26901. inline void clearMultiple (int num) noexcept { memset (data, 128, num) ;}
  26902. template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsInt32LE (source.getAsInt32()); }
  26903. template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsInt32BE (source.getAsInt32()); }
  26904. inline void copyFromSameType (UInt8& source) noexcept { *data = *source.data; }
  26905. uint8* data;
  26906. enum { bytesPerSample = 1, maxValue = 0x7f, resolution = (1 << 24), isFloat = 0 };
  26907. };
  26908. class Int16
  26909. {
  26910. public:
  26911. inline Int16 (void* data_) noexcept : data (static_cast <uint16*> (data_)) {}
  26912. inline void advance() noexcept { ++data; }
  26913. inline void skip (int numSamples) noexcept { data += numSamples; }
  26914. inline float getAsFloatLE() const noexcept { return (float) ((1.0 / (1.0 + maxValue)) * (int16) ByteOrder::swapIfBigEndian (*data)); }
  26915. inline float getAsFloatBE() const noexcept { return (float) ((1.0 / (1.0 + maxValue)) * (int16) ByteOrder::swapIfLittleEndian (*data)); }
  26916. inline void setAsFloatLE (float newValue) noexcept { *data = ByteOrder::swapIfBigEndian ((uint16) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue)))); }
  26917. inline void setAsFloatBE (float newValue) noexcept { *data = ByteOrder::swapIfLittleEndian ((uint16) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue)))); }
  26918. inline int32 getAsInt32LE() const noexcept { return (int32) (ByteOrder::swapIfBigEndian ((uint16) *data) << 16); }
  26919. inline int32 getAsInt32BE() const noexcept { return (int32) (ByteOrder::swapIfLittleEndian ((uint16) *data) << 16); }
  26920. inline void setAsInt32LE (int32 newValue) noexcept { *data = ByteOrder::swapIfBigEndian ((uint16) (newValue >> 16)); }
  26921. inline void setAsInt32BE (int32 newValue) noexcept { *data = ByteOrder::swapIfLittleEndian ((uint16) (newValue >> 16)); }
  26922. inline void clear() noexcept { *data = 0; }
  26923. inline void clearMultiple (int num) noexcept { zeromem (data, num * bytesPerSample) ;}
  26924. template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsInt32LE (source.getAsInt32()); }
  26925. template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsInt32BE (source.getAsInt32()); }
  26926. inline void copyFromSameType (Int16& source) noexcept { *data = *source.data; }
  26927. uint16* data;
  26928. enum { bytesPerSample = 2, maxValue = 0x7fff, resolution = (1 << 16), isFloat = 0 };
  26929. };
  26930. class Int24
  26931. {
  26932. public:
  26933. inline Int24 (void* data_) noexcept : data (static_cast <char*> (data_)) {}
  26934. inline void advance() noexcept { data += 3; }
  26935. inline void skip (int numSamples) noexcept { data += 3 * numSamples; }
  26936. inline float getAsFloatLE() const noexcept { return (float) (ByteOrder::littleEndian24Bit (data) * (1.0 / (1.0 + maxValue))); }
  26937. inline float getAsFloatBE() const noexcept { return (float) (ByteOrder::bigEndian24Bit (data) * (1.0 / (1.0 + maxValue))); }
  26938. inline void setAsFloatLE (float newValue) noexcept { ByteOrder::littleEndian24BitToChars (jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue))), data); }
  26939. inline void setAsFloatBE (float newValue) noexcept { ByteOrder::bigEndian24BitToChars (jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue))), data); }
  26940. inline int32 getAsInt32LE() const noexcept { return (int32) ByteOrder::littleEndian24Bit (data) << 8; }
  26941. inline int32 getAsInt32BE() const noexcept { return (int32) ByteOrder::bigEndian24Bit (data) << 8; }
  26942. inline void setAsInt32LE (int32 newValue) noexcept { ByteOrder::littleEndian24BitToChars (newValue >> 8, data); }
  26943. inline void setAsInt32BE (int32 newValue) noexcept { ByteOrder::bigEndian24BitToChars (newValue >> 8, data); }
  26944. inline void clear() noexcept { data[0] = 0; data[1] = 0; data[2] = 0; }
  26945. inline void clearMultiple (int num) noexcept { zeromem (data, num * bytesPerSample) ;}
  26946. template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsInt32LE (source.getAsInt32()); }
  26947. template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsInt32BE (source.getAsInt32()); }
  26948. inline void copyFromSameType (Int24& source) noexcept { data[0] = source.data[0]; data[1] = source.data[1]; data[2] = source.data[2]; }
  26949. char* data;
  26950. enum { bytesPerSample = 3, maxValue = 0x7fffff, resolution = (1 << 8), isFloat = 0 };
  26951. };
  26952. class Int32
  26953. {
  26954. public:
  26955. inline Int32 (void* data_) noexcept : data (static_cast <uint32*> (data_)) {}
  26956. inline void advance() noexcept { ++data; }
  26957. inline void skip (int numSamples) noexcept { data += numSamples; }
  26958. inline float getAsFloatLE() const noexcept { return (float) ((1.0 / (1.0 + maxValue)) * (int32) ByteOrder::swapIfBigEndian (*data)); }
  26959. inline float getAsFloatBE() const noexcept { return (float) ((1.0 / (1.0 + maxValue)) * (int32) ByteOrder::swapIfLittleEndian (*data)); }
  26960. inline void setAsFloatLE (float newValue) noexcept { *data = ByteOrder::swapIfBigEndian ((uint32) (maxValue * jlimit (-1.0, 1.0, (double) newValue))); }
  26961. inline void setAsFloatBE (float newValue) noexcept { *data = ByteOrder::swapIfLittleEndian ((uint32) (maxValue * jlimit (-1.0, 1.0, (double) newValue))); }
  26962. inline int32 getAsInt32LE() const noexcept { return (int32) ByteOrder::swapIfBigEndian (*data); }
  26963. inline int32 getAsInt32BE() const noexcept { return (int32) ByteOrder::swapIfLittleEndian (*data); }
  26964. inline void setAsInt32LE (int32 newValue) noexcept { *data = ByteOrder::swapIfBigEndian ((uint32) newValue); }
  26965. inline void setAsInt32BE (int32 newValue) noexcept { *data = ByteOrder::swapIfLittleEndian ((uint32) newValue); }
  26966. inline void clear() noexcept { *data = 0; }
  26967. inline void clearMultiple (int num) noexcept { zeromem (data, num * bytesPerSample) ;}
  26968. template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsInt32LE (source.getAsInt32()); }
  26969. template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsInt32BE (source.getAsInt32()); }
  26970. inline void copyFromSameType (Int32& source) noexcept { *data = *source.data; }
  26971. uint32* data;
  26972. enum { bytesPerSample = 4, maxValue = 0x7fffffff, resolution = 1, isFloat = 0 };
  26973. };
  26974. class Float32
  26975. {
  26976. public:
  26977. inline Float32 (void* data_) noexcept : data (static_cast <float*> (data_)) {}
  26978. inline void advance() noexcept { ++data; }
  26979. inline void skip (int numSamples) noexcept { data += numSamples; }
  26980. #if JUCE_BIG_ENDIAN
  26981. inline float getAsFloatBE() const noexcept { return *data; }
  26982. inline void setAsFloatBE (float newValue) noexcept { *data = newValue; }
  26983. inline float getAsFloatLE() const noexcept { union { uint32 asInt; float asFloat; } n; n.asInt = ByteOrder::swap (*(uint32*) data); return n.asFloat; }
  26984. inline void setAsFloatLE (float newValue) noexcept { union { uint32 asInt; float asFloat; } n; n.asFloat = newValue; *(uint32*) data = ByteOrder::swap (n.asInt); }
  26985. #else
  26986. inline float getAsFloatLE() const noexcept { return *data; }
  26987. inline void setAsFloatLE (float newValue) noexcept { *data = newValue; }
  26988. inline float getAsFloatBE() const noexcept { union { uint32 asInt; float asFloat; } n; n.asInt = ByteOrder::swap (*(uint32*) data); return n.asFloat; }
  26989. inline void setAsFloatBE (float newValue) noexcept { union { uint32 asInt; float asFloat; } n; n.asFloat = newValue; *(uint32*) data = ByteOrder::swap (n.asInt); }
  26990. #endif
  26991. inline int32 getAsInt32LE() const noexcept { return (int32) roundToInt (jlimit (-1.0, 1.0, (double) getAsFloatLE()) * (double) maxValue); }
  26992. inline int32 getAsInt32BE() const noexcept { return (int32) roundToInt (jlimit (-1.0, 1.0, (double) getAsFloatBE()) * (double) maxValue); }
  26993. inline void setAsInt32LE (int32 newValue) noexcept { setAsFloatLE ((float) (newValue * (1.0 / (1.0 + maxValue)))); }
  26994. inline void setAsInt32BE (int32 newValue) noexcept { setAsFloatBE ((float) (newValue * (1.0 / (1.0 + maxValue)))); }
  26995. inline void clear() noexcept { *data = 0; }
  26996. inline void clearMultiple (int num) noexcept { zeromem (data, num * bytesPerSample) ;}
  26997. template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsFloatLE (source.getAsFloat()); }
  26998. template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsFloatBE (source.getAsFloat()); }
  26999. inline void copyFromSameType (Float32& source) noexcept { *data = *source.data; }
  27000. float* data;
  27001. enum { bytesPerSample = 4, maxValue = 0x7fffffff, resolution = (1 << 8), isFloat = 1 };
  27002. };
  27003. class NonInterleaved
  27004. {
  27005. public:
  27006. inline NonInterleaved() noexcept {}
  27007. inline NonInterleaved (const NonInterleaved&) noexcept {}
  27008. inline NonInterleaved (const int) noexcept {}
  27009. inline void copyFrom (const NonInterleaved&) noexcept {}
  27010. template <class SampleFormatType> inline void advanceData (SampleFormatType& s) noexcept { s.advance(); }
  27011. template <class SampleFormatType> inline void advanceDataBy (SampleFormatType& s, int numSamples) noexcept { s.skip (numSamples); }
  27012. template <class SampleFormatType> inline void clear (SampleFormatType& s, int numSamples) noexcept { s.clearMultiple (numSamples); }
  27013. template <class SampleFormatType> inline static int getNumBytesBetweenSamples (const SampleFormatType&) noexcept { return SampleFormatType::bytesPerSample; }
  27014. enum { isInterleavedType = 0, numInterleavedChannels = 1 };
  27015. };
  27016. class Interleaved
  27017. {
  27018. public:
  27019. inline Interleaved() noexcept : numInterleavedChannels (1) {}
  27020. inline Interleaved (const Interleaved& other) noexcept : numInterleavedChannels (other.numInterleavedChannels) {}
  27021. inline Interleaved (const int numInterleavedChannels_) noexcept : numInterleavedChannels (numInterleavedChannels_) {}
  27022. inline void copyFrom (const Interleaved& other) noexcept { numInterleavedChannels = other.numInterleavedChannels; }
  27023. template <class SampleFormatType> inline void advanceData (SampleFormatType& s) noexcept { s.skip (numInterleavedChannels); }
  27024. template <class SampleFormatType> inline void advanceDataBy (SampleFormatType& s, int numSamples) noexcept { s.skip (numInterleavedChannels * numSamples); }
  27025. template <class SampleFormatType> inline void clear (SampleFormatType& s, int numSamples) noexcept { while (--numSamples >= 0) { s.clear(); s.skip (numInterleavedChannels); } }
  27026. template <class SampleFormatType> inline int getNumBytesBetweenSamples (const SampleFormatType&) const noexcept { return numInterleavedChannels * SampleFormatType::bytesPerSample; }
  27027. int numInterleavedChannels;
  27028. enum { isInterleavedType = 1 };
  27029. };
  27030. class NonConst
  27031. {
  27032. public:
  27033. typedef void VoidType;
  27034. static inline void* toVoidPtr (VoidType* v) noexcept { return v; }
  27035. enum { isConst = 0 };
  27036. };
  27037. class Const
  27038. {
  27039. public:
  27040. typedef const void VoidType;
  27041. static inline void* toVoidPtr (VoidType* v) noexcept { return const_cast<void*> (v); }
  27042. enum { isConst = 1 };
  27043. };
  27044. #endif
  27045. /**
  27046. A pointer to a block of audio data with a particular encoding.
  27047. This object can be used to read and write from blocks of encoded audio samples. To create one, you specify
  27048. the audio format as a series of template parameters, e.g.
  27049. @code
  27050. // this creates a pointer for reading from a const array of 16-bit little-endian packed samples.
  27051. AudioData::Pointer <AudioData::Int16,
  27052. AudioData::LittleEndian,
  27053. AudioData::NonInterleaved,
  27054. AudioData::Const> pointer (someRawAudioData);
  27055. // These methods read the sample that is being pointed to
  27056. float firstSampleAsFloat = pointer.getAsFloat();
  27057. int32 firstSampleAsInt = pointer.getAsInt32();
  27058. ++pointer; // moves the pointer to the next sample.
  27059. pointer += 3; // skips the next 3 samples.
  27060. @endcode
  27061. The convertSamples() method lets you copy a range of samples from one format to another, automatically
  27062. converting its format.
  27063. @see AudioData::Converter
  27064. */
  27065. template <typename SampleFormat,
  27066. typename Endianness,
  27067. typename InterleavingType,
  27068. typename Constness>
  27069. class Pointer
  27070. {
  27071. public:
  27072. /** Creates a non-interleaved pointer from some raw data in the appropriate format.
  27073. This constructor is only used if you've specified the AudioData::NonInterleaved option -
  27074. for interleaved formats, use the constructor that also takes a number of channels.
  27075. */
  27076. Pointer (typename Constness::VoidType* sourceData) noexcept
  27077. : data (Constness::toVoidPtr (sourceData))
  27078. {
  27079. // If you're using interleaved data, call the other constructor! If you're using non-interleaved data,
  27080. // you should pass NonInterleaved as the template parameter for the interleaving type!
  27081. static_jassert (InterleavingType::isInterleavedType == 0);
  27082. }
  27083. /** Creates a pointer from some raw data in the appropriate format with the specified number of interleaved channels.
  27084. For non-interleaved data, use the other constructor.
  27085. */
  27086. Pointer (typename Constness::VoidType* sourceData, int numInterleavedChannels) noexcept
  27087. : data (Constness::toVoidPtr (sourceData)),
  27088. interleaving (numInterleavedChannels)
  27089. {
  27090. }
  27091. /** Creates a copy of another pointer. */
  27092. Pointer (const Pointer& other) noexcept
  27093. : data (other.data),
  27094. interleaving (other.interleaving)
  27095. {
  27096. }
  27097. Pointer& operator= (const Pointer& other) noexcept
  27098. {
  27099. data = other.data;
  27100. interleaving.copyFrom (other.interleaving);
  27101. return *this;
  27102. }
  27103. /** Returns the value of the first sample as a floating point value.
  27104. The value will be in the range -1.0 to 1.0 for integer formats. For floating point
  27105. formats, the value could be outside that range, although -1 to 1 is the standard range.
  27106. */
  27107. inline float getAsFloat() const noexcept { return Endianness::getAsFloat (data); }
  27108. /** Sets the value of the first sample as a floating point value.
  27109. (This method can only be used if the AudioData::NonConst option was used).
  27110. The value should be in the range -1.0 to 1.0 - for integer formats, values outside that
  27111. range will be clipped. For floating point formats, any value passed in here will be
  27112. written directly, although -1 to 1 is the standard range.
  27113. */
  27114. inline void setAsFloat (float newValue) noexcept
  27115. {
  27116. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  27117. Endianness::setAsFloat (data, newValue);
  27118. }
  27119. /** Returns the value of the first sample as a 32-bit integer.
  27120. The value returned will be in the range 0x80000000 to 0x7fffffff, and shorter values will be
  27121. shifted to fill this range (e.g. if you're reading from 24-bit data, the values will be shifted up
  27122. by 8 bits when returned here). If the source data is floating point, values beyond -1.0 to 1.0 will
  27123. be clipped so that -1.0 maps onto -0x7fffffff and 1.0 maps to 0x7fffffff.
  27124. */
  27125. inline int32 getAsInt32() const noexcept { return Endianness::getAsInt32 (data); }
  27126. /** Sets the value of the first sample as a 32-bit integer.
  27127. This will be mapped to the range of the format that is being written - see getAsInt32().
  27128. */
  27129. inline void setAsInt32 (int32 newValue) noexcept
  27130. {
  27131. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  27132. Endianness::setAsInt32 (data, newValue);
  27133. }
  27134. /** Moves the pointer along to the next sample. */
  27135. inline Pointer& operator++() noexcept { advance(); return *this; }
  27136. /** Moves the pointer back to the previous sample. */
  27137. inline Pointer& operator--() noexcept { interleaving.advanceDataBy (data, -1); return *this; }
  27138. /** Adds a number of samples to the pointer's position. */
  27139. Pointer& operator+= (int samplesToJump) noexcept { interleaving.advanceDataBy (data, samplesToJump); return *this; }
  27140. /** Writes a stream of samples into this pointer from another pointer.
  27141. This will copy the specified number of samples, converting between formats appropriately.
  27142. */
  27143. void convertSamples (Pointer source, int numSamples) const noexcept
  27144. {
  27145. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  27146. Pointer dest (*this);
  27147. while (--numSamples >= 0)
  27148. {
  27149. dest.data.copyFromSameType (source.data);
  27150. dest.advance();
  27151. source.advance();
  27152. }
  27153. }
  27154. /** Writes a stream of samples into this pointer from another pointer.
  27155. This will copy the specified number of samples, converting between formats appropriately.
  27156. */
  27157. template <class OtherPointerType>
  27158. void convertSamples (OtherPointerType source, int numSamples) const noexcept
  27159. {
  27160. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  27161. Pointer dest (*this);
  27162. if (source.getRawData() != getRawData() || source.getNumBytesBetweenSamples() >= getNumBytesBetweenSamples())
  27163. {
  27164. while (--numSamples >= 0)
  27165. {
  27166. Endianness::copyFrom (dest.data, source);
  27167. dest.advance();
  27168. ++source;
  27169. }
  27170. }
  27171. else // copy backwards if we're increasing the sample width..
  27172. {
  27173. dest += numSamples;
  27174. source += numSamples;
  27175. while (--numSamples >= 0)
  27176. Endianness::copyFrom ((--dest).data, --source);
  27177. }
  27178. }
  27179. /** Sets a number of samples to zero. */
  27180. void clearSamples (int numSamples) const noexcept
  27181. {
  27182. Pointer dest (*this);
  27183. dest.interleaving.clear (dest.data, numSamples);
  27184. }
  27185. /** Returns true if the pointer is using a floating-point format. */
  27186. static bool isFloatingPoint() noexcept { return (bool) SampleFormat::isFloat; }
  27187. /** Returns true if the format is big-endian. */
  27188. static bool isBigEndian() noexcept { return (bool) Endianness::isBigEndian; }
  27189. /** Returns the number of bytes in each sample (ignoring the number of interleaved channels). */
  27190. static int getBytesPerSample() noexcept { return (int) SampleFormat::bytesPerSample; }
  27191. /** Returns the number of interleaved channels in the format. */
  27192. int getNumInterleavedChannels() const noexcept { return (int) this->numInterleavedChannels; }
  27193. /** Returns the number of bytes between the start address of each sample. */
  27194. int getNumBytesBetweenSamples() const noexcept { return interleaving.getNumBytesBetweenSamples (data); }
  27195. /** Returns the accuracy of this format when represented as a 32-bit integer.
  27196. This is the smallest number above 0 that can be represented in the sample format, converted to
  27197. a 32-bit range. E,g. if the format is 8-bit, its resolution is 0x01000000; if the format is 24-bit,
  27198. its resolution is 0x100.
  27199. */
  27200. static int get32BitResolution() noexcept { return (int) SampleFormat::resolution; }
  27201. /** Returns a pointer to the underlying data. */
  27202. const void* getRawData() const noexcept { return data.data; }
  27203. private:
  27204. SampleFormat data;
  27205. InterleavingType interleaving; // annoyingly, making the interleaving type a superclass to take
  27206. // advantage of EBCO causes an internal compiler error in VC6..
  27207. inline void advance() noexcept { interleaving.advanceData (data); }
  27208. Pointer operator++ (int); // private to force you to use the more efficient pre-increment!
  27209. Pointer operator-- (int);
  27210. };
  27211. /** A base class for objects that are used to convert between two different sample formats.
  27212. The AudioData::ConverterInstance implements this base class and can be templated, so
  27213. you can create an instance that converts between two particular formats, and then
  27214. store this in the abstract base class.
  27215. @see AudioData::ConverterInstance
  27216. */
  27217. class Converter
  27218. {
  27219. public:
  27220. virtual ~Converter() {}
  27221. /** Converts a sequence of samples from the converter's source format into the dest format. */
  27222. virtual void convertSamples (void* destSamples, const void* sourceSamples, int numSamples) const = 0;
  27223. /** Converts a sequence of samples from the converter's source format into the dest format.
  27224. This method takes sub-channel indexes, which can be used with interleaved formats in order to choose a
  27225. particular sub-channel of the data to be used.
  27226. */
  27227. virtual void convertSamples (void* destSamples, int destSubChannel,
  27228. const void* sourceSamples, int sourceSubChannel, int numSamples) const = 0;
  27229. };
  27230. /**
  27231. A class that converts between two templated AudioData::Pointer types, and which
  27232. implements the AudioData::Converter interface.
  27233. This can be used as a concrete instance of the AudioData::Converter abstract class.
  27234. @see AudioData::Converter
  27235. */
  27236. template <class SourceSampleType, class DestSampleType>
  27237. class ConverterInstance : public Converter
  27238. {
  27239. public:
  27240. ConverterInstance (int numSourceChannels = 1, int numDestChannels = 1)
  27241. : sourceChannels (numSourceChannels), destChannels (numDestChannels)
  27242. {}
  27243. ~ConverterInstance() {}
  27244. void convertSamples (void* dest, const void* source, int numSamples) const
  27245. {
  27246. SourceSampleType s (source, sourceChannels);
  27247. DestSampleType d (dest, destChannels);
  27248. d.convertSamples (s, numSamples);
  27249. }
  27250. void convertSamples (void* dest, int destSubChannel,
  27251. const void* source, int sourceSubChannel, int numSamples) const
  27252. {
  27253. jassert (destSubChannel < destChannels && sourceSubChannel < sourceChannels);
  27254. SourceSampleType s (addBytesToPointer (source, sourceSubChannel * SourceSampleType::getBytesPerSample()), sourceChannels);
  27255. DestSampleType d (addBytesToPointer (dest, destSubChannel * DestSampleType::getBytesPerSample()), destChannels);
  27256. d.convertSamples (s, numSamples);
  27257. }
  27258. private:
  27259. JUCE_DECLARE_NON_COPYABLE (ConverterInstance);
  27260. const int sourceChannels, destChannels;
  27261. };
  27262. };
  27263. /**
  27264. A set of routines to convert buffers of 32-bit floating point data to and from
  27265. various integer formats.
  27266. Note that these functions are deprecated - the AudioData class provides a much more
  27267. flexible set of conversion classes now.
  27268. */
  27269. class JUCE_API AudioDataConverters
  27270. {
  27271. public:
  27272. static void convertFloatToInt16LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  27273. static void convertFloatToInt16BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  27274. static void convertFloatToInt24LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  27275. static void convertFloatToInt24BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  27276. static void convertFloatToInt32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27277. static void convertFloatToInt32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27278. static void convertFloatToFloat32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27279. static void convertFloatToFloat32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27280. static void convertInt16LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  27281. static void convertInt16BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  27282. static void convertInt24LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  27283. static void convertInt24BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  27284. static void convertInt32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27285. static void convertInt32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27286. static void convertFloat32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27287. static void convertFloat32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27288. enum DataFormat
  27289. {
  27290. int16LE,
  27291. int16BE,
  27292. int24LE,
  27293. int24BE,
  27294. int32LE,
  27295. int32BE,
  27296. float32LE,
  27297. float32BE,
  27298. };
  27299. static void convertFloatToFormat (DataFormat destFormat,
  27300. const float* source, void* dest, int numSamples);
  27301. static void convertFormatToFloat (DataFormat sourceFormat,
  27302. const void* source, float* dest, int numSamples);
  27303. static void interleaveSamples (const float** source, float* dest,
  27304. int numSamples, int numChannels);
  27305. static void deinterleaveSamples (const float* source, float** dest,
  27306. int numSamples, int numChannels);
  27307. private:
  27308. AudioDataConverters();
  27309. JUCE_DECLARE_NON_COPYABLE (AudioDataConverters);
  27310. };
  27311. #endif // __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  27312. /*** End of inlined file: juce_AudioDataConverters.h ***/
  27313. class AudioFormat;
  27314. /**
  27315. Reads samples from an audio file stream.
  27316. A subclass that reads a specific type of audio format will be created by
  27317. an AudioFormat object.
  27318. @see AudioFormat, AudioFormatWriter
  27319. */
  27320. class JUCE_API AudioFormatReader
  27321. {
  27322. protected:
  27323. /** Creates an AudioFormatReader object.
  27324. @param sourceStream the stream to read from - this will be deleted
  27325. by this object when it is no longer needed. (Some
  27326. specialised readers might not use this parameter and
  27327. can leave it as 0).
  27328. @param formatName the description that will be returned by the getFormatName()
  27329. method
  27330. */
  27331. AudioFormatReader (InputStream* sourceStream,
  27332. const String& formatName);
  27333. public:
  27334. /** Destructor. */
  27335. virtual ~AudioFormatReader();
  27336. /** Returns a description of what type of format this is.
  27337. E.g. "AIFF"
  27338. */
  27339. const String& getFormatName() const noexcept { return formatName; }
  27340. /** Reads samples from the stream.
  27341. @param destSamples an array of buffers into which the sample data for each
  27342. channel will be written.
  27343. If the format is fixed-point, each channel will be written
  27344. as an array of 32-bit signed integers using the full
  27345. range -0x80000000 to 0x7fffffff, regardless of the source's
  27346. bit-depth. If it is a floating-point format, you should cast
  27347. the resulting array to a (float**) to get the values (in the
  27348. range -1.0 to 1.0 or beyond)
  27349. If the format is stereo, then destSamples[0] is the left channel
  27350. data, and destSamples[1] is the right channel.
  27351. The numDestChannels parameter indicates how many pointers this array
  27352. contains, but some of these pointers can be null if you don't want to
  27353. read data for some of the channels
  27354. @param numDestChannels the number of array elements in the destChannels array
  27355. @param startSampleInSource the position in the audio file or stream at which the samples
  27356. should be read, as a number of samples from the start of the
  27357. stream. It's ok for this to be beyond the start or end of the
  27358. available data - any samples that are out-of-range will be returned
  27359. as zeros.
  27360. @param numSamplesToRead the number of samples to read. If this is greater than the number
  27361. of samples that the file or stream contains. the result will be padded
  27362. with zeros
  27363. @param fillLeftoverChannelsWithCopies if true, this indicates that if there's no source data available
  27364. for some of the channels that you pass in, then they should be filled with
  27365. copies of valid source channels.
  27366. E.g. if you're reading a mono file and you pass 2 channels to this method, then
  27367. if fillLeftoverChannelsWithCopies is true, both destination channels will be filled
  27368. with the same data from the file's single channel. If fillLeftoverChannelsWithCopies
  27369. was false, then only the first channel would be filled with the file's contents, and
  27370. the second would be cleared. If there are many channels, e.g. you try to read 4 channels
  27371. from a stereo file, then the last 3 would all end up with copies of the same data.
  27372. @returns true if the operation succeeded, false if there was an error. Note
  27373. that reading sections of data beyond the extent of the stream isn't an
  27374. error - the reader should just return zeros for these regions
  27375. @see readMaxLevels
  27376. */
  27377. bool read (int* const* destSamples,
  27378. int numDestChannels,
  27379. int64 startSampleInSource,
  27380. int numSamplesToRead,
  27381. bool fillLeftoverChannelsWithCopies);
  27382. /** Finds the highest and lowest sample levels from a section of the audio stream.
  27383. This will read a block of samples from the stream, and measure the
  27384. highest and lowest sample levels from the channels in that section, returning
  27385. these as normalised floating-point levels.
  27386. @param startSample the offset into the audio stream to start reading from. It's
  27387. ok for this to be beyond the start or end of the stream.
  27388. @param numSamples how many samples to read
  27389. @param lowestLeft on return, this is the lowest absolute sample from the left channel
  27390. @param highestLeft on return, this is the highest absolute sample from the left channel
  27391. @param lowestRight on return, this is the lowest absolute sample from the right
  27392. channel (if there is one)
  27393. @param highestRight on return, this is the highest absolute sample from the right
  27394. channel (if there is one)
  27395. @see read
  27396. */
  27397. virtual void readMaxLevels (int64 startSample,
  27398. int64 numSamples,
  27399. float& lowestLeft,
  27400. float& highestLeft,
  27401. float& lowestRight,
  27402. float& highestRight);
  27403. /** Scans the source looking for a sample whose magnitude is in a specified range.
  27404. This will read from the source, either forwards or backwards between two sample
  27405. positions, until it finds a sample whose magnitude lies between two specified levels.
  27406. If it finds a suitable sample, it returns its position; if not, it will return -1.
  27407. There's also a minimumConsecutiveSamples setting to help avoid spikes or zero-crossing
  27408. points when you're searching for a continuous range of samples
  27409. @param startSample the first sample to look at
  27410. @param numSamplesToSearch the number of samples to scan. If this value is negative,
  27411. the search will go backwards
  27412. @param magnitudeRangeMinimum the lowest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  27413. @param magnitudeRangeMaximum the highest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  27414. @param minimumConsecutiveSamples if this is > 0, the method will only look for a sequence
  27415. of this many consecutive samples, all of which lie
  27416. within the target range. When it finds such a sequence,
  27417. it returns the position of the first in-range sample
  27418. it found (i.e. the earliest one if scanning forwards, the
  27419. latest one if scanning backwards)
  27420. */
  27421. int64 searchForLevel (int64 startSample,
  27422. int64 numSamplesToSearch,
  27423. double magnitudeRangeMinimum,
  27424. double magnitudeRangeMaximum,
  27425. int minimumConsecutiveSamples);
  27426. /** The sample-rate of the stream. */
  27427. double sampleRate;
  27428. /** The number of bits per sample, e.g. 16, 24, 32. */
  27429. unsigned int bitsPerSample;
  27430. /** The total number of samples in the audio stream. */
  27431. int64 lengthInSamples;
  27432. /** The total number of channels in the audio stream. */
  27433. unsigned int numChannels;
  27434. /** Indicates whether the data is floating-point or fixed. */
  27435. bool usesFloatingPointData;
  27436. /** A set of metadata values that the reader has pulled out of the stream.
  27437. Exactly what these values are depends on the format, so you can
  27438. check out the format implementation code to see what kind of stuff
  27439. they understand.
  27440. */
  27441. StringPairArray metadataValues;
  27442. /** The input stream, for use by subclasses. */
  27443. InputStream* input;
  27444. /** Subclasses must implement this method to perform the low-level read operation.
  27445. Callers should use read() instead of calling this directly.
  27446. @param destSamples the array of destination buffers to fill. Some of these
  27447. pointers may be null
  27448. @param numDestChannels the number of items in the destSamples array. This
  27449. value is guaranteed not to be greater than the number of
  27450. channels that this reader object contains
  27451. @param startOffsetInDestBuffer the number of samples from the start of the
  27452. dest data at which to begin writing
  27453. @param startSampleInFile the number of samples into the source data at which
  27454. to begin reading. This value is guaranteed to be >= 0.
  27455. @param numSamples the number of samples to read
  27456. */
  27457. virtual bool readSamples (int** destSamples,
  27458. int numDestChannels,
  27459. int startOffsetInDestBuffer,
  27460. int64 startSampleInFile,
  27461. int numSamples) = 0;
  27462. protected:
  27463. /** Used by AudioFormatReader subclasses to copy data to different formats. */
  27464. template <class DestSampleType, class SourceSampleType, class SourceEndianness>
  27465. struct ReadHelper
  27466. {
  27467. typedef AudioData::Pointer <DestSampleType, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestType;
  27468. typedef AudioData::Pointer <SourceSampleType, SourceEndianness, AudioData::Interleaved, AudioData::Const> SourceType;
  27469. static void read (int** destData, int destOffset, int numDestChannels, const void* sourceData, int numSourceChannels, int numSamples) noexcept
  27470. {
  27471. for (int i = 0; i < numDestChannels; ++i)
  27472. {
  27473. if (destData[i] != nullptr)
  27474. {
  27475. DestType dest (destData[i]);
  27476. dest += destOffset;
  27477. if (i < numSourceChannels)
  27478. dest.convertSamples (SourceType (addBytesToPointer (sourceData, i * SourceType::getBytesPerSample()), numSourceChannels), numSamples);
  27479. else
  27480. dest.clearSamples (numSamples);
  27481. }
  27482. }
  27483. }
  27484. };
  27485. private:
  27486. String formatName;
  27487. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatReader);
  27488. };
  27489. #endif // __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  27490. /*** End of inlined file: juce_AudioFormatReader.h ***/
  27491. /*** Start of inlined file: juce_AudioFormatWriter.h ***/
  27492. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27493. #define __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27494. /*** Start of inlined file: juce_AudioSource.h ***/
  27495. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  27496. #define __JUCE_AUDIOSOURCE_JUCEHEADER__
  27497. /*** Start of inlined file: juce_AudioSampleBuffer.h ***/
  27498. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  27499. #define __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  27500. class AudioFormatReader;
  27501. class AudioFormatWriter;
  27502. /**
  27503. A multi-channel buffer of 32-bit floating point audio samples.
  27504. */
  27505. class JUCE_API AudioSampleBuffer
  27506. {
  27507. public:
  27508. /** Creates a buffer with a specified number of channels and samples.
  27509. The contents of the buffer will initially be undefined, so use clear() to
  27510. set all the samples to zero.
  27511. The buffer will allocate its memory internally, and this will be released
  27512. when the buffer is deleted.
  27513. */
  27514. AudioSampleBuffer (int numChannels,
  27515. int numSamples) noexcept;
  27516. /** Creates a buffer using a pre-allocated block of memory.
  27517. Note that if the buffer is resized or its number of channels is changed, it
  27518. will re-allocate memory internally and copy the existing data to this new area,
  27519. so it will then stop directly addressing this memory.
  27520. @param dataToReferTo a pre-allocated array containing pointers to the data
  27521. for each channel that should be used by this buffer. The
  27522. buffer will only refer to this memory, it won't try to delete
  27523. it when the buffer is deleted or resized.
  27524. @param numChannels the number of channels to use - this must correspond to the
  27525. number of elements in the array passed in
  27526. @param numSamples the number of samples to use - this must correspond to the
  27527. size of the arrays passed in
  27528. */
  27529. AudioSampleBuffer (float** dataToReferTo,
  27530. int numChannels,
  27531. int numSamples) noexcept;
  27532. /** Creates a buffer using a pre-allocated block of memory.
  27533. Note that if the buffer is resized or its number of channels is changed, it
  27534. will re-allocate memory internally and copy the existing data to this new area,
  27535. so it will then stop directly addressing this memory.
  27536. @param dataToReferTo a pre-allocated array containing pointers to the data
  27537. for each channel that should be used by this buffer. The
  27538. buffer will only refer to this memory, it won't try to delete
  27539. it when the buffer is deleted or resized.
  27540. @param numChannels the number of channels to use - this must correspond to the
  27541. number of elements in the array passed in
  27542. @param startSample the offset within the arrays at which the data begins
  27543. @param numSamples the number of samples to use - this must correspond to the
  27544. size of the arrays passed in
  27545. */
  27546. AudioSampleBuffer (float** dataToReferTo,
  27547. int numChannels,
  27548. int startSample,
  27549. int numSamples) noexcept;
  27550. /** Copies another buffer.
  27551. This buffer will make its own copy of the other's data, unless the buffer was created
  27552. using an external data buffer, in which case boths buffers will just point to the same
  27553. shared block of data.
  27554. */
  27555. AudioSampleBuffer (const AudioSampleBuffer& other) noexcept;
  27556. /** Copies another buffer onto this one.
  27557. This buffer's size will be changed to that of the other buffer.
  27558. */
  27559. AudioSampleBuffer& operator= (const AudioSampleBuffer& other) noexcept;
  27560. /** Destructor.
  27561. This will free any memory allocated by the buffer.
  27562. */
  27563. virtual ~AudioSampleBuffer() noexcept;
  27564. /** Returns the number of channels of audio data that this buffer contains.
  27565. @see getSampleData
  27566. */
  27567. int getNumChannels() const noexcept { return numChannels; }
  27568. /** Returns the number of samples allocated in each of the buffer's channels.
  27569. @see getSampleData
  27570. */
  27571. int getNumSamples() const noexcept { return size; }
  27572. /** Returns a pointer one of the buffer's channels.
  27573. For speed, this doesn't check whether the channel number is out of range,
  27574. so be careful when using it!
  27575. */
  27576. float* getSampleData (const int channelNumber) const noexcept
  27577. {
  27578. jassert (isPositiveAndBelow (channelNumber, numChannels));
  27579. return channels [channelNumber];
  27580. }
  27581. /** Returns a pointer to a sample in one of the buffer's channels.
  27582. For speed, this doesn't check whether the channel and sample number
  27583. are out-of-range, so be careful when using it!
  27584. */
  27585. float* getSampleData (const int channelNumber,
  27586. const int sampleOffset) const noexcept
  27587. {
  27588. jassert (isPositiveAndBelow (channelNumber, numChannels));
  27589. jassert (isPositiveAndBelow (sampleOffset, size));
  27590. return channels [channelNumber] + sampleOffset;
  27591. }
  27592. /** Returns an array of pointers to the channels in the buffer.
  27593. Don't modify any of the pointers that are returned, and bear in mind that
  27594. these will become invalid if the buffer is resized.
  27595. */
  27596. float** getArrayOfChannels() const noexcept { return channels; }
  27597. /** Changes the buffer's size or number of channels.
  27598. This can expand or contract the buffer's length, and add or remove channels.
  27599. If keepExistingContent is true, it will try to preserve as much of the
  27600. old data as it can in the new buffer.
  27601. If clearExtraSpace is true, then any extra channels or space that is
  27602. allocated will be also be cleared. If false, then this space is left
  27603. uninitialised.
  27604. If avoidReallocating is true, then changing the buffer's size won't reduce the
  27605. amount of memory that is currently allocated (but it will still increase it if
  27606. the new size is bigger than the amount it currently has). If this is false, then
  27607. a new allocation will be done so that the buffer uses takes up the minimum amount
  27608. of memory that it needs.
  27609. */
  27610. void setSize (int newNumChannels,
  27611. int newNumSamples,
  27612. bool keepExistingContent = false,
  27613. bool clearExtraSpace = false,
  27614. bool avoidReallocating = false) noexcept;
  27615. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  27616. There's also a constructor that lets you specify arrays like this, but this
  27617. lets you change the channels dynamically.
  27618. Note that if the buffer is resized or its number of channels is changed, it
  27619. will re-allocate memory internally and copy the existing data to this new area,
  27620. so it will then stop directly addressing this memory.
  27621. @param dataToReferTo a pre-allocated array containing pointers to the data
  27622. for each channel that should be used by this buffer. The
  27623. buffer will only refer to this memory, it won't try to delete
  27624. it when the buffer is deleted or resized.
  27625. @param numChannels the number of channels to use - this must correspond to the
  27626. number of elements in the array passed in
  27627. @param numSamples the number of samples to use - this must correspond to the
  27628. size of the arrays passed in
  27629. */
  27630. void setDataToReferTo (float** dataToReferTo,
  27631. int numChannels,
  27632. int numSamples) noexcept;
  27633. /** Clears all the samples in all channels. */
  27634. void clear() noexcept;
  27635. /** Clears a specified region of all the channels.
  27636. For speed, this doesn't check whether the channel and sample number
  27637. are in-range, so be careful!
  27638. */
  27639. void clear (int startSample,
  27640. int numSamples) noexcept;
  27641. /** Clears a specified region of just one channel.
  27642. For speed, this doesn't check whether the channel and sample number
  27643. are in-range, so be careful!
  27644. */
  27645. void clear (int channel,
  27646. int startSample,
  27647. int numSamples) noexcept;
  27648. /** Applies a gain multiple to a region of one channel.
  27649. For speed, this doesn't check whether the channel and sample number
  27650. are in-range, so be careful!
  27651. */
  27652. void applyGain (int channel,
  27653. int startSample,
  27654. int numSamples,
  27655. float gain) noexcept;
  27656. /** Applies a gain multiple to a region of all the channels.
  27657. For speed, this doesn't check whether the sample numbers
  27658. are in-range, so be careful!
  27659. */
  27660. void applyGain (int startSample,
  27661. int numSamples,
  27662. float gain) noexcept;
  27663. /** Applies a range of gains to a region of a channel.
  27664. The gain that is applied to each sample will vary from
  27665. startGain on the first sample to endGain on the last Sample,
  27666. so it can be used to do basic fades.
  27667. For speed, this doesn't check whether the sample numbers
  27668. are in-range, so be careful!
  27669. */
  27670. void applyGainRamp (int channel,
  27671. int startSample,
  27672. int numSamples,
  27673. float startGain,
  27674. float endGain) noexcept;
  27675. /** Adds samples from another buffer to this one.
  27676. @param destChannel the channel within this buffer to add the samples to
  27677. @param destStartSample the start sample within this buffer's channel
  27678. @param source the source buffer to add from
  27679. @param sourceChannel the channel within the source buffer to read from
  27680. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  27681. @param numSamples the number of samples to process
  27682. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  27683. added to this buffer's samples
  27684. @see copyFrom
  27685. */
  27686. void addFrom (int destChannel,
  27687. int destStartSample,
  27688. const AudioSampleBuffer& source,
  27689. int sourceChannel,
  27690. int sourceStartSample,
  27691. int numSamples,
  27692. float gainToApplyToSource = 1.0f) noexcept;
  27693. /** Adds samples from an array of floats to one of the channels.
  27694. @param destChannel the channel within this buffer to add the samples to
  27695. @param destStartSample the start sample within this buffer's channel
  27696. @param source the source data to use
  27697. @param numSamples the number of samples to process
  27698. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  27699. added to this buffer's samples
  27700. @see copyFrom
  27701. */
  27702. void addFrom (int destChannel,
  27703. int destStartSample,
  27704. const float* source,
  27705. int numSamples,
  27706. float gainToApplyToSource = 1.0f) noexcept;
  27707. /** Adds samples from an array of floats, applying a gain ramp to them.
  27708. @param destChannel the channel within this buffer to add the samples to
  27709. @param destStartSample the start sample within this buffer's channel
  27710. @param source the source data to use
  27711. @param numSamples the number of samples to process
  27712. @param startGain the gain to apply to the first sample (this is multiplied with
  27713. the source samples before they are added to this buffer)
  27714. @param endGain the gain to apply to the final sample. The gain is linearly
  27715. interpolated between the first and last samples.
  27716. */
  27717. void addFromWithRamp (int destChannel,
  27718. int destStartSample,
  27719. const float* source,
  27720. int numSamples,
  27721. float startGain,
  27722. float endGain) noexcept;
  27723. /** Copies samples from another buffer to this one.
  27724. @param destChannel the channel within this buffer to copy the samples to
  27725. @param destStartSample the start sample within this buffer's channel
  27726. @param source the source buffer to read from
  27727. @param sourceChannel the channel within the source buffer to read from
  27728. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  27729. @param numSamples the number of samples to process
  27730. @see addFrom
  27731. */
  27732. void copyFrom (int destChannel,
  27733. int destStartSample,
  27734. const AudioSampleBuffer& source,
  27735. int sourceChannel,
  27736. int sourceStartSample,
  27737. int numSamples) noexcept;
  27738. /** Copies samples from an array of floats into one of the channels.
  27739. @param destChannel the channel within this buffer to copy the samples to
  27740. @param destStartSample the start sample within this buffer's channel
  27741. @param source the source buffer to read from
  27742. @param numSamples the number of samples to process
  27743. @see addFrom
  27744. */
  27745. void copyFrom (int destChannel,
  27746. int destStartSample,
  27747. const float* source,
  27748. int numSamples) noexcept;
  27749. /** Copies samples from an array of floats into one of the channels, applying a gain to it.
  27750. @param destChannel the channel within this buffer to copy the samples to
  27751. @param destStartSample the start sample within this buffer's channel
  27752. @param source the source buffer to read from
  27753. @param numSamples the number of samples to process
  27754. @param gain the gain to apply
  27755. @see addFrom
  27756. */
  27757. void copyFrom (int destChannel,
  27758. int destStartSample,
  27759. const float* source,
  27760. int numSamples,
  27761. float gain) noexcept;
  27762. /** Copies samples from an array of floats into one of the channels, applying a gain ramp.
  27763. @param destChannel the channel within this buffer to copy the samples to
  27764. @param destStartSample the start sample within this buffer's channel
  27765. @param source the source buffer to read from
  27766. @param numSamples the number of samples to process
  27767. @param startGain the gain to apply to the first sample (this is multiplied with
  27768. the source samples before they are copied to this buffer)
  27769. @param endGain the gain to apply to the final sample. The gain is linearly
  27770. interpolated between the first and last samples.
  27771. @see addFrom
  27772. */
  27773. void copyFromWithRamp (int destChannel,
  27774. int destStartSample,
  27775. const float* source,
  27776. int numSamples,
  27777. float startGain,
  27778. float endGain) noexcept;
  27779. /** Finds the highest and lowest sample values in a given range.
  27780. @param channel the channel to read from
  27781. @param startSample the start sample within the channel
  27782. @param numSamples the number of samples to check
  27783. @param minVal on return, the lowest value that was found
  27784. @param maxVal on return, the highest value that was found
  27785. */
  27786. void findMinMax (int channel,
  27787. int startSample,
  27788. int numSamples,
  27789. float& minVal,
  27790. float& maxVal) const noexcept;
  27791. /** Finds the highest absolute sample value within a region of a channel.
  27792. */
  27793. float getMagnitude (int channel,
  27794. int startSample,
  27795. int numSamples) const noexcept;
  27796. /** Finds the highest absolute sample value within a region on all channels.
  27797. */
  27798. float getMagnitude (int startSample,
  27799. int numSamples) const noexcept;
  27800. /** Returns the root mean squared level for a region of a channel.
  27801. */
  27802. float getRMSLevel (int channel,
  27803. int startSample,
  27804. int numSamples) const noexcept;
  27805. /** Fills a section of the buffer using an AudioReader as its source.
  27806. This will convert the reader's fixed- or floating-point data to
  27807. the buffer's floating-point format, and will try to intelligently
  27808. cope with mismatches between the number of channels in the reader
  27809. and the buffer.
  27810. @see writeToAudioWriter
  27811. */
  27812. void readFromAudioReader (AudioFormatReader* reader,
  27813. int startSample,
  27814. int numSamples,
  27815. int64 readerStartSample,
  27816. bool useReaderLeftChan,
  27817. bool useReaderRightChan);
  27818. /** Writes a section of this buffer to an audio writer.
  27819. This saves you having to mess about with channels or floating/fixed
  27820. point conversion.
  27821. @see readFromAudioReader
  27822. */
  27823. void writeToAudioWriter (AudioFormatWriter* writer,
  27824. int startSample,
  27825. int numSamples) const;
  27826. private:
  27827. int numChannels, size;
  27828. size_t allocatedBytes;
  27829. float** channels;
  27830. HeapBlock <char> allocatedData;
  27831. float* preallocatedChannelSpace [32];
  27832. void allocateData();
  27833. void allocateChannels (float** dataToReferTo, int offset);
  27834. JUCE_LEAK_DETECTOR (AudioSampleBuffer);
  27835. };
  27836. #endif // __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  27837. /*** End of inlined file: juce_AudioSampleBuffer.h ***/
  27838. /**
  27839. Used by AudioSource::getNextAudioBlock().
  27840. */
  27841. struct JUCE_API AudioSourceChannelInfo
  27842. {
  27843. /** The destination buffer to fill with audio data.
  27844. When the AudioSource::getNextAudioBlock() method is called, the active section
  27845. of this buffer should be filled with whatever output the source produces.
  27846. Only the samples specified by the startSample and numSamples members of this structure
  27847. should be affected by the call.
  27848. The contents of the buffer when it is passed to the the AudioSource::getNextAudioBlock()
  27849. method can be treated as the input if the source is performing some kind of filter operation,
  27850. but should be cleared if this is not the case - the clearActiveBufferRegion() is
  27851. a handy way of doing this.
  27852. The number of channels in the buffer could be anything, so the AudioSource
  27853. must cope with this in whatever way is appropriate for its function.
  27854. */
  27855. AudioSampleBuffer* buffer;
  27856. /** The first sample in the buffer from which the callback is expected
  27857. to write data. */
  27858. int startSample;
  27859. /** The number of samples in the buffer which the callback is expected to
  27860. fill with data. */
  27861. int numSamples;
  27862. /** Convenient method to clear the buffer if the source is not producing any data. */
  27863. void clearActiveBufferRegion() const
  27864. {
  27865. if (buffer != nullptr)
  27866. buffer->clear (startSample, numSamples);
  27867. }
  27868. };
  27869. /**
  27870. Base class for objects that can produce a continuous stream of audio.
  27871. An AudioSource has two states: 'prepared' and 'unprepared'.
  27872. When a source needs to be played, it is first put into a 'prepared' state by a call to
  27873. prepareToPlay(), and then repeated calls will be made to its getNextAudioBlock() method to
  27874. process the audio data.
  27875. Once playback has finished, the releaseResources() method is called to put the stream
  27876. back into an 'unprepared' state.
  27877. @see AudioFormatReaderSource, ResamplingAudioSource
  27878. */
  27879. class JUCE_API AudioSource
  27880. {
  27881. protected:
  27882. /** Creates an AudioSource. */
  27883. AudioSource() noexcept {}
  27884. public:
  27885. /** Destructor. */
  27886. virtual ~AudioSource() {}
  27887. /** Tells the source to prepare for playing.
  27888. An AudioSource has two states: prepared and unprepared.
  27889. The prepareToPlay() method is guaranteed to be called at least once on an 'unpreprared'
  27890. source to put it into a 'prepared' state before any calls will be made to getNextAudioBlock().
  27891. This callback allows the source to initialise any resources it might need when playing.
  27892. Once playback has finished, the releaseResources() method is called to put the stream
  27893. back into an 'unprepared' state.
  27894. Note that this method could be called more than once in succession without
  27895. a matching call to releaseResources(), so make sure your code is robust and
  27896. can handle that kind of situation.
  27897. @param samplesPerBlockExpected the number of samples that the source
  27898. will be expected to supply each time its
  27899. getNextAudioBlock() method is called. This
  27900. number may vary slightly, because it will be dependent
  27901. on audio hardware callbacks, and these aren't
  27902. guaranteed to always use a constant block size, so
  27903. the source should be able to cope with small variations.
  27904. @param sampleRate the sample rate that the output will be used at - this
  27905. is needed by sources such as tone generators.
  27906. @see releaseResources, getNextAudioBlock
  27907. */
  27908. virtual void prepareToPlay (int samplesPerBlockExpected,
  27909. double sampleRate) = 0;
  27910. /** Allows the source to release anything it no longer needs after playback has stopped.
  27911. This will be called when the source is no longer going to have its getNextAudioBlock()
  27912. method called, so it should release any spare memory, etc. that it might have
  27913. allocated during the prepareToPlay() call.
  27914. Note that there's no guarantee that prepareToPlay() will actually have been called before
  27915. releaseResources(), and it may be called more than once in succession, so make sure your
  27916. code is robust and doesn't make any assumptions about when it will be called.
  27917. @see prepareToPlay, getNextAudioBlock
  27918. */
  27919. virtual void releaseResources() = 0;
  27920. /** Called repeatedly to fetch subsequent blocks of audio data.
  27921. After calling the prepareToPlay() method, this callback will be made each
  27922. time the audio playback hardware (or whatever other destination the audio
  27923. data is going to) needs another block of data.
  27924. It will generally be called on a high-priority system thread, or possibly even
  27925. an interrupt, so be careful not to do too much work here, as that will cause
  27926. audio glitches!
  27927. @see AudioSourceChannelInfo, prepareToPlay, releaseResources
  27928. */
  27929. virtual void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) = 0;
  27930. };
  27931. #endif // __JUCE_AUDIOSOURCE_JUCEHEADER__
  27932. /*** End of inlined file: juce_AudioSource.h ***/
  27933. class AudioThumbnail;
  27934. /**
  27935. Writes samples to an audio file stream.
  27936. A subclass that writes a specific type of audio format will be created by
  27937. an AudioFormat object.
  27938. After creating one of these with the AudioFormat::createWriterFor() method
  27939. you can call its write() method to store the samples, and then delete it.
  27940. @see AudioFormat, AudioFormatReader
  27941. */
  27942. class JUCE_API AudioFormatWriter
  27943. {
  27944. protected:
  27945. /** Creates an AudioFormatWriter object.
  27946. @param destStream the stream to write to - this will be deleted
  27947. by this object when it is no longer needed
  27948. @param formatName the description that will be returned by the getFormatName()
  27949. method
  27950. @param sampleRate the sample rate to use - the base class just stores
  27951. this value, it doesn't do anything with it
  27952. @param numberOfChannels the number of channels to write - the base class just stores
  27953. this value, it doesn't do anything with it
  27954. @param bitsPerSample the bit depth of the stream - the base class just stores
  27955. this value, it doesn't do anything with it
  27956. */
  27957. AudioFormatWriter (OutputStream* destStream,
  27958. const String& formatName,
  27959. double sampleRate,
  27960. unsigned int numberOfChannels,
  27961. unsigned int bitsPerSample);
  27962. public:
  27963. /** Destructor. */
  27964. virtual ~AudioFormatWriter();
  27965. /** Returns a description of what type of format this is.
  27966. E.g. "AIFF file"
  27967. */
  27968. const String& getFormatName() const noexcept { return formatName; }
  27969. /** Writes a set of samples to the audio stream.
  27970. Note that if you're trying to write the contents of an AudioSampleBuffer, you
  27971. can use AudioSampleBuffer::writeToAudioWriter().
  27972. @param samplesToWrite an array of arrays containing the sample data for
  27973. each channel to write. This is a zero-terminated
  27974. array of arrays, and can contain a different number
  27975. of channels than the actual stream uses, and the
  27976. writer should do its best to cope with this.
  27977. If the format is fixed-point, each channel will be formatted
  27978. as an array of signed integers using the full 32-bit
  27979. range -0x80000000 to 0x7fffffff, regardless of the source's
  27980. bit-depth. If it is a floating-point format, you should treat
  27981. the arrays as arrays of floats, and just cast it to an (int**)
  27982. to pass it into the method.
  27983. @param numSamples the number of samples to write
  27984. */
  27985. virtual bool write (const int** samplesToWrite,
  27986. int numSamples) = 0;
  27987. /** Reads a section of samples from an AudioFormatReader, and writes these to
  27988. the output.
  27989. This will take care of any floating-point conversion that's required to convert
  27990. between the two formats. It won't deal with sample-rate conversion, though.
  27991. If numSamplesToRead < 0, it will write the entire length of the reader.
  27992. @returns false if it can't read or write properly during the operation
  27993. */
  27994. bool writeFromAudioReader (AudioFormatReader& reader,
  27995. int64 startSample,
  27996. int64 numSamplesToRead);
  27997. /** Reads some samples from an AudioSource, and writes these to the output.
  27998. The source must already have been initialised with the AudioSource::prepareToPlay() method
  27999. @param source the source to read from
  28000. @param numSamplesToRead total number of samples to read and write
  28001. @param samplesPerBlock the maximum number of samples to fetch from the source
  28002. @returns false if it can't read or write properly during the operation
  28003. */
  28004. bool writeFromAudioSource (AudioSource& source,
  28005. int numSamplesToRead,
  28006. int samplesPerBlock = 2048);
  28007. /** Writes some samples from an AudioSampleBuffer.
  28008. */
  28009. bool writeFromAudioSampleBuffer (const AudioSampleBuffer& source,
  28010. int startSample, int numSamples);
  28011. /** Returns the sample rate being used. */
  28012. double getSampleRate() const noexcept { return sampleRate; }
  28013. /** Returns the number of channels being written. */
  28014. int getNumChannels() const noexcept { return numChannels; }
  28015. /** Returns the bit-depth of the data being written. */
  28016. int getBitsPerSample() const noexcept { return bitsPerSample; }
  28017. /** Returns true if it's a floating-point format, false if it's fixed-point. */
  28018. bool isFloatingPoint() const noexcept { return usesFloatingPointData; }
  28019. /**
  28020. Provides a FIFO for an AudioFormatWriter, allowing you to push incoming
  28021. data into a buffer which will be flushed to disk by a background thread.
  28022. */
  28023. class ThreadedWriter
  28024. {
  28025. public:
  28026. /** Creates a ThreadedWriter for a given writer and a thread.
  28027. The writer object which is passed in here will be owned and deleted by
  28028. the ThreadedWriter when it is no longer needed.
  28029. To stop the writer and flush the buffer to disk, simply delete this object.
  28030. */
  28031. ThreadedWriter (AudioFormatWriter* writer,
  28032. TimeSliceThread& backgroundThread,
  28033. int numSamplesToBuffer);
  28034. /** Destructor. */
  28035. ~ThreadedWriter();
  28036. /** Pushes some incoming audio data into the FIFO.
  28037. If there's enough free space in the buffer, this will add the data to it,
  28038. If the FIFO is too full to accept this many samples, the method will return
  28039. false - then you could either wait until the background thread has had time to
  28040. consume some of the buffered data and try again, or you can give up
  28041. and lost this block.
  28042. The data must be an array containing the same number of channels as the
  28043. AudioFormatWriter object is using. None of these channels can be null.
  28044. */
  28045. bool write (const float** data, int numSamples);
  28046. /** Allows you to specify a thumbnail that this writer should update with the
  28047. incoming data.
  28048. The thumbnail will be cleared and will the writer will begin adding data to
  28049. it as it arrives. Pass a null pointer to stop the writer updating any thumbnails.
  28050. */
  28051. void setThumbnailToUpdate (AudioThumbnail* thumbnailToUpdate);
  28052. #ifndef DOXYGEN
  28053. class Buffer; // (only public for VC6 compatibility)
  28054. #endif
  28055. private:
  28056. friend class ScopedPointer<Buffer>;
  28057. ScopedPointer<Buffer> buffer;
  28058. };
  28059. protected:
  28060. /** The sample rate of the stream. */
  28061. double sampleRate;
  28062. /** The number of channels being written to the stream. */
  28063. unsigned int numChannels;
  28064. /** The bit depth of the file. */
  28065. unsigned int bitsPerSample;
  28066. /** True if it's a floating-point format, false if it's fixed-point. */
  28067. bool usesFloatingPointData;
  28068. /** The output stream for Use by subclasses. */
  28069. OutputStream* output;
  28070. /** Used by AudioFormatWriter subclasses to copy data to different formats. */
  28071. template <class DestSampleType, class SourceSampleType, class DestEndianness>
  28072. struct WriteHelper
  28073. {
  28074. typedef AudioData::Pointer <DestSampleType, DestEndianness, AudioData::Interleaved, AudioData::NonConst> DestType;
  28075. typedef AudioData::Pointer <SourceSampleType, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
  28076. static void write (void* destData, int numDestChannels, const int** source,
  28077. int numSamples, const int sourceOffset = 0) noexcept
  28078. {
  28079. for (int i = 0; i < numDestChannels; ++i)
  28080. {
  28081. const DestType dest (addBytesToPointer (destData, i * DestType::getBytesPerSample()), numDestChannels);
  28082. if (*source != nullptr)
  28083. {
  28084. dest.convertSamples (SourceType (*source + sourceOffset), numSamples);
  28085. ++source;
  28086. }
  28087. else
  28088. {
  28089. dest.clearSamples (numSamples);
  28090. }
  28091. }
  28092. }
  28093. };
  28094. private:
  28095. String formatName;
  28096. friend class ThreadedWriter;
  28097. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatWriter);
  28098. };
  28099. #endif // __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  28100. /*** End of inlined file: juce_AudioFormatWriter.h ***/
  28101. /**
  28102. Subclasses of AudioFormat are used to read and write different audio
  28103. file formats.
  28104. @see AudioFormatReader, AudioFormatWriter, WavAudioFormat, AiffAudioFormat
  28105. */
  28106. class JUCE_API AudioFormat
  28107. {
  28108. public:
  28109. /** Destructor. */
  28110. virtual ~AudioFormat();
  28111. /** Returns the name of this format.
  28112. e.g. "WAV file" or "AIFF file"
  28113. */
  28114. const String& getFormatName() const;
  28115. /** Returns all the file extensions that might apply to a file of this format.
  28116. The first item will be the one that's preferred when creating a new file.
  28117. So for a wav file this might just return ".wav"; for an AIFF file it might
  28118. return two items, ".aif" and ".aiff"
  28119. */
  28120. const StringArray& getFileExtensions() const;
  28121. /** Returns true if this the given file can be read by this format.
  28122. Subclasses shouldn't do too much work here, just check the extension or
  28123. file type. The base class implementation just checks the file's extension
  28124. against one of the ones that was registered in the constructor.
  28125. */
  28126. virtual bool canHandleFile (const File& fileToTest);
  28127. /** Returns a set of sample rates that the format can read and write. */
  28128. virtual const Array <int> getPossibleSampleRates() = 0;
  28129. /** Returns a set of bit depths that the format can read and write. */
  28130. virtual const Array <int> getPossibleBitDepths() = 0;
  28131. /** Returns true if the format can do 2-channel audio. */
  28132. virtual bool canDoStereo() = 0;
  28133. /** Returns true if the format can do 1-channel audio. */
  28134. virtual bool canDoMono() = 0;
  28135. /** Returns true if the format uses compressed data. */
  28136. virtual bool isCompressed();
  28137. /** Returns a list of different qualities that can be used when writing.
  28138. Non-compressed formats will just return an empty array, but for something
  28139. like Ogg-Vorbis or MP3, it might return a list of bit-rates, etc.
  28140. When calling createWriterFor(), an index from this array is passed in to
  28141. tell the format which option is required.
  28142. */
  28143. virtual StringArray getQualityOptions();
  28144. /** Tries to create an object that can read from a stream containing audio
  28145. data in this format.
  28146. The reader object that is returned can be used to read from the stream, and
  28147. should then be deleted by the caller.
  28148. @param sourceStream the stream to read from - the AudioFormatReader object
  28149. that is returned will delete this stream when it no longer
  28150. needs it.
  28151. @param deleteStreamIfOpeningFails if no reader can be created, this determines whether this method
  28152. should delete the stream object that was passed-in. (If a valid
  28153. reader is returned, it will always be in charge of deleting the
  28154. stream, so this parameter is ignored)
  28155. @see AudioFormatReader
  28156. */
  28157. virtual AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28158. bool deleteStreamIfOpeningFails) = 0;
  28159. /** Tries to create an object that can write to a stream with this audio format.
  28160. The writer object that is returned can be used to write to the stream, and
  28161. should then be deleted by the caller.
  28162. If the stream can't be created for some reason (e.g. the parameters passed in
  28163. here aren't suitable), this will return 0.
  28164. @param streamToWriteTo the stream that the data will go to - this will be
  28165. deleted by the AudioFormatWriter object when it's no longer
  28166. needed. If no AudioFormatWriter can be created by this method,
  28167. the stream will NOT be deleted, so that the caller can re-use it
  28168. to try to open a different format, etc
  28169. @param sampleRateToUse the sample rate for the file, which must be one of the ones
  28170. returned by getPossibleSampleRates()
  28171. @param numberOfChannels the number of channels - this must be either 1 or 2, and
  28172. the choice will depend on the results of canDoMono() and
  28173. canDoStereo()
  28174. @param bitsPerSample the bits per sample to use - this must be one of the values
  28175. returned by getPossibleBitDepths()
  28176. @param metadataValues a set of metadata values that the writer should try to write
  28177. to the stream. Exactly what these are depends on the format,
  28178. and the subclass doesn't actually have to do anything with
  28179. them if it doesn't want to. Have a look at the specific format
  28180. implementation classes to see possible values that can be
  28181. used
  28182. @param qualityOptionIndex the index of one of compression qualities returned by the
  28183. getQualityOptions() method. If there aren't any quality options
  28184. for this format, just pass 0 in this parameter, as it'll be
  28185. ignored
  28186. @see AudioFormatWriter
  28187. */
  28188. virtual AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28189. double sampleRateToUse,
  28190. unsigned int numberOfChannels,
  28191. int bitsPerSample,
  28192. const StringPairArray& metadataValues,
  28193. int qualityOptionIndex) = 0;
  28194. protected:
  28195. /** Creates an AudioFormat object.
  28196. @param formatName this sets the value that will be returned by getFormatName()
  28197. @param fileExtensions a zero-terminated list of file extensions - this is what will
  28198. be returned by getFileExtension()
  28199. */
  28200. AudioFormat (const String& formatName,
  28201. const StringArray& fileExtensions);
  28202. private:
  28203. String formatName;
  28204. StringArray fileExtensions;
  28205. };
  28206. #endif // __JUCE_AUDIOFORMAT_JUCEHEADER__
  28207. /*** End of inlined file: juce_AudioFormat.h ***/
  28208. /**
  28209. Reads and Writes AIFF format audio files.
  28210. @see AudioFormat
  28211. */
  28212. class JUCE_API AiffAudioFormat : public AudioFormat
  28213. {
  28214. public:
  28215. /** Creates an format object. */
  28216. AiffAudioFormat();
  28217. /** Destructor. */
  28218. ~AiffAudioFormat();
  28219. const Array <int> getPossibleSampleRates();
  28220. const Array <int> getPossibleBitDepths();
  28221. bool canDoStereo();
  28222. bool canDoMono();
  28223. #if JUCE_MAC
  28224. bool canHandleFile (const File& fileToTest);
  28225. #endif
  28226. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28227. bool deleteStreamIfOpeningFails);
  28228. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28229. double sampleRateToUse,
  28230. unsigned int numberOfChannels,
  28231. int bitsPerSample,
  28232. const StringPairArray& metadataValues,
  28233. int qualityOptionIndex);
  28234. private:
  28235. JUCE_LEAK_DETECTOR (AiffAudioFormat);
  28236. };
  28237. #endif // __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  28238. /*** End of inlined file: juce_AiffAudioFormat.h ***/
  28239. #endif
  28240. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  28241. /*** Start of inlined file: juce_AudioCDBurner.h ***/
  28242. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  28243. #define __JUCE_AUDIOCDBURNER_JUCEHEADER__
  28244. #if JUCE_USE_CDBURNER || DOXYGEN
  28245. /**
  28246. */
  28247. class AudioCDBurner : public ChangeBroadcaster
  28248. {
  28249. public:
  28250. /** Returns a list of available optical drives.
  28251. Use openDevice() to open one of the items from this list.
  28252. */
  28253. static StringArray findAvailableDevices();
  28254. /** Tries to open one of the optical drives.
  28255. The deviceIndex is an index into the array returned by findAvailableDevices().
  28256. */
  28257. static AudioCDBurner* openDevice (const int deviceIndex);
  28258. /** Destructor. */
  28259. ~AudioCDBurner();
  28260. enum DiskState
  28261. {
  28262. unknown, /**< An error condition, if the device isn't responding. */
  28263. trayOpen, /**< The drive is currently open. Note that a slot-loading drive
  28264. may seem to be permanently open. */
  28265. noDisc, /**< The drive has no disk in it. */
  28266. writableDiskPresent, /**< The drive contains a writeable disk. */
  28267. readOnlyDiskPresent /**< The drive contains a read-only disk. */
  28268. };
  28269. /** Returns the current status of the device.
  28270. To get informed when the drive's status changes, attach a ChangeListener to
  28271. the AudioCDBurner.
  28272. */
  28273. DiskState getDiskState() const;
  28274. /** Returns true if there's a writable disk in the drive. */
  28275. bool isDiskPresent() const;
  28276. /** Sends an eject signal to the drive.
  28277. The eject will happen asynchronously, so you can use getDiskState() and
  28278. waitUntilStateChange() to monitor its progress.
  28279. */
  28280. bool openTray();
  28281. /** Blocks the current thread until the drive's state changes, or until the timeout expires.
  28282. @returns the device's new state
  28283. */
  28284. DiskState waitUntilStateChange (int timeOutMilliseconds);
  28285. /** Returns the set of possible write speeds that the device can handle.
  28286. These are as a multiple of 'normal' speed, so e.g. '24x' returns 24, etc.
  28287. Note that if there's no media present in the drive, this value may be unavailable!
  28288. @see setWriteSpeed, getWriteSpeed
  28289. */
  28290. Array<int> getAvailableWriteSpeeds() const;
  28291. /** Tries to enable or disable buffer underrun safety on devices that support it.
  28292. @returns true if it's now enabled. If the device doesn't support it, this
  28293. will always return false.
  28294. */
  28295. bool setBufferUnderrunProtection (bool shouldBeEnabled);
  28296. /** Returns the number of free blocks on the disk.
  28297. There are 75 blocks per second, at 44100Hz.
  28298. */
  28299. int getNumAvailableAudioBlocks() const;
  28300. /** Adds a track to be written.
  28301. The source passed-in here will be kept by this object, and it will
  28302. be used and deleted at some point in the future, either during the
  28303. burn() method or when this AudioCDBurner object is deleted. Your caller
  28304. method shouldn't keep a reference to it or use it again after passing
  28305. it in here.
  28306. */
  28307. bool addAudioTrack (AudioSource* source, int numSamples);
  28308. /** Receives progress callbacks during a cd-burn operation.
  28309. @see AudioCDBurner::burn()
  28310. */
  28311. class BurnProgressListener
  28312. {
  28313. public:
  28314. BurnProgressListener() noexcept {}
  28315. virtual ~BurnProgressListener() {}
  28316. /** Called at intervals to report on the progress of the AudioCDBurner.
  28317. To cancel the burn, return true from this method.
  28318. */
  28319. virtual bool audioCDBurnProgress (float proportionComplete) = 0;
  28320. };
  28321. /** Runs the burn process.
  28322. This method will block until the operation is complete.
  28323. @param listener the object to receive callbacks about progress
  28324. @param ejectDiscAfterwards whether to eject the disk after the burn completes
  28325. @param performFakeBurnForTesting if true, no data will actually be written to the disk
  28326. @param writeSpeed one of the write speeds from getAvailableWriteSpeeds(), or
  28327. 0 or less to mean the fastest speed.
  28328. */
  28329. String burn (BurnProgressListener* listener,
  28330. bool ejectDiscAfterwards,
  28331. bool performFakeBurnForTesting,
  28332. int writeSpeed);
  28333. /** If a burn operation is currently in progress, this tells it to stop
  28334. as soon as possible.
  28335. It's also possible to stop the burn process by returning true from
  28336. BurnProgressListener::audioCDBurnProgress()
  28337. */
  28338. void abortBurn();
  28339. private:
  28340. AudioCDBurner (const int deviceIndex);
  28341. class Pimpl;
  28342. friend class ScopedPointer<Pimpl>;
  28343. ScopedPointer<Pimpl> pimpl;
  28344. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioCDBurner);
  28345. };
  28346. #endif
  28347. #endif // __JUCE_AUDIOCDBURNER_JUCEHEADER__
  28348. /*** End of inlined file: juce_AudioCDBurner.h ***/
  28349. #endif
  28350. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  28351. /*** Start of inlined file: juce_AudioCDReader.h ***/
  28352. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  28353. #define __JUCE_AUDIOCDREADER_JUCEHEADER__
  28354. #if JUCE_USE_CDREADER || DOXYGEN
  28355. #if JUCE_MAC
  28356. #endif
  28357. /**
  28358. A type of AudioFormatReader that reads from an audio CD.
  28359. One of these can be used to read a CD as if it's one big audio stream. Use the
  28360. getPositionOfTrackStart() method to find where the individual tracks are
  28361. within the stream.
  28362. @see AudioFormatReader
  28363. */
  28364. class JUCE_API AudioCDReader : public AudioFormatReader
  28365. {
  28366. public:
  28367. /** Returns a list of names of Audio CDs currently available for reading.
  28368. If there's a CD drive but no CD in it, this might return an empty list, or
  28369. possibly a device that can be opened but which has no tracks, depending
  28370. on the platform.
  28371. @see createReaderForCD
  28372. */
  28373. static StringArray getAvailableCDNames();
  28374. /** Tries to create an AudioFormatReader that can read from an Audio CD.
  28375. @param index the index of one of the available CDs - use getAvailableCDNames()
  28376. to find out how many there are.
  28377. @returns a new AudioCDReader object, or 0 if it couldn't be created. The
  28378. caller will be responsible for deleting the object returned.
  28379. */
  28380. static AudioCDReader* createReaderForCD (const int index);
  28381. /** Destructor. */
  28382. ~AudioCDReader();
  28383. /** Implementation of the AudioFormatReader method. */
  28384. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  28385. int64 startSampleInFile, int numSamples);
  28386. /** Checks whether the CD has been removed from the drive.
  28387. */
  28388. bool isCDStillPresent() const;
  28389. /** Returns the total number of tracks (audio + data).
  28390. */
  28391. int getNumTracks() const;
  28392. /** Finds the sample offset of the start of a track.
  28393. @param trackNum the track number, where trackNum = 0 is the first track
  28394. and trackNum = getNumTracks() means the end of the CD.
  28395. */
  28396. int getPositionOfTrackStart (int trackNum) const;
  28397. /** Returns true if a given track is an audio track.
  28398. @param trackNum the track number, where 0 is the first track.
  28399. */
  28400. bool isTrackAudio (int trackNum) const;
  28401. /** Returns an array of sample offsets for the start of each track, followed by
  28402. the sample position of the end of the CD.
  28403. */
  28404. const Array<int>& getTrackOffsets() const;
  28405. /** Refreshes the object's table of contents.
  28406. If the disc has been ejected and a different one put in since this
  28407. object was created, this will cause it to update its idea of how many tracks
  28408. there are, etc.
  28409. */
  28410. void refreshTrackLengths();
  28411. /** Enables scanning for indexes within tracks.
  28412. @see getLastIndex
  28413. */
  28414. void enableIndexScanning (bool enabled);
  28415. /** Returns the index number found during the last read() call.
  28416. Index scanning is turned off by default - turn it on with enableIndexScanning().
  28417. Then when the read() method is called, if it comes across an index within that
  28418. block, the index number is stored and returned by this method.
  28419. Some devices might not support indexes, of course.
  28420. (If you don't know what CD indexes are, it's unlikely you'll ever need them).
  28421. @see enableIndexScanning
  28422. */
  28423. int getLastIndex() const;
  28424. /** Scans a track to find the position of any indexes within it.
  28425. @param trackNumber the track to look in, where 0 is the first track on the disc
  28426. @returns an array of sample positions of any index points found (not including
  28427. the index that marks the start of the track)
  28428. */
  28429. const Array <int> findIndexesInTrack (const int trackNumber);
  28430. /** Returns the CDDB id number for the CD.
  28431. It's not a great way of identifying a disc, but it's traditional.
  28432. */
  28433. int getCDDBId();
  28434. /** Tries to eject the disk.
  28435. Of course this might not be possible, if some other process is using it.
  28436. */
  28437. void ejectDisk();
  28438. enum
  28439. {
  28440. framesPerSecond = 75,
  28441. samplesPerFrame = 44100 / framesPerSecond
  28442. };
  28443. private:
  28444. Array<int> trackStartSamples;
  28445. #if JUCE_MAC
  28446. File volumeDir;
  28447. Array<File> tracks;
  28448. int currentReaderTrack;
  28449. ScopedPointer <AudioFormatReader> reader;
  28450. AudioCDReader (const File& volume);
  28451. #elif JUCE_WINDOWS
  28452. bool audioTracks [100];
  28453. void* handle;
  28454. MemoryBlock buffer;
  28455. bool indexingEnabled;
  28456. int lastIndex, firstFrameInBuffer, samplesInBuffer;
  28457. AudioCDReader (void* handle);
  28458. int getIndexAt (int samplePos);
  28459. #elif JUCE_LINUX
  28460. AudioCDReader();
  28461. #endif
  28462. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioCDReader);
  28463. };
  28464. #endif
  28465. #endif // __JUCE_AUDIOCDREADER_JUCEHEADER__
  28466. /*** End of inlined file: juce_AudioCDReader.h ***/
  28467. #endif
  28468. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  28469. #endif
  28470. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  28471. /*** Start of inlined file: juce_AudioFormatManager.h ***/
  28472. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  28473. #define __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  28474. /**
  28475. A class for keeping a list of available audio formats, and for deciding which
  28476. one to use to open a given file.
  28477. You can either use this class as a singleton object, or create instances of it
  28478. yourself. Once created, use its registerFormat() method to tell it which
  28479. formats it should use.
  28480. @see AudioFormat
  28481. */
  28482. class JUCE_API AudioFormatManager
  28483. {
  28484. public:
  28485. /** Creates an empty format manager.
  28486. Before it'll be any use, you'll need to call registerFormat() with all the
  28487. formats you want it to be able to recognise.
  28488. */
  28489. AudioFormatManager();
  28490. /** Destructor. */
  28491. ~AudioFormatManager();
  28492. /** Adds a format to the manager's list of available file types.
  28493. The object passed-in will be deleted by this object, so don't keep a pointer
  28494. to it!
  28495. If makeThisTheDefaultFormat is true, then the getDefaultFormat() method will
  28496. return this one when called.
  28497. */
  28498. void registerFormat (AudioFormat* newFormat,
  28499. bool makeThisTheDefaultFormat);
  28500. /** Handy method to make it easy to register the formats that come with Juce.
  28501. Currently, this will add WAV and AIFF to the list.
  28502. */
  28503. void registerBasicFormats();
  28504. /** Clears the list of known formats. */
  28505. void clearFormats();
  28506. /** Returns the number of currently registered file formats. */
  28507. int getNumKnownFormats() const;
  28508. /** Returns one of the registered file formats. */
  28509. AudioFormat* getKnownFormat (int index) const;
  28510. /** Looks for which of the known formats is listed as being for a given file
  28511. extension.
  28512. The extension may have a dot before it, so e.g. ".wav" or "wav" are both ok.
  28513. */
  28514. AudioFormat* findFormatForFileExtension (const String& fileExtension) const;
  28515. /** Returns the format which has been set as the default one.
  28516. You can set a format as being the default when it is registered. It's useful
  28517. when you want to write to a file, because the best format may change between
  28518. platforms, e.g. AIFF is preferred on the Mac, WAV on Windows.
  28519. If none has been set as the default, this method will just return the first
  28520. one in the list.
  28521. */
  28522. AudioFormat* getDefaultFormat() const;
  28523. /** Returns a set of wildcards for file-matching that contains the extensions for
  28524. all known formats.
  28525. E.g. if might return "*.wav;*.aiff" if it just knows about wavs and aiffs.
  28526. */
  28527. String getWildcardForAllFormats() const;
  28528. /** Searches through the known formats to try to create a suitable reader for
  28529. this file.
  28530. If none of the registered formats can open the file, it'll return 0. If it
  28531. returns a reader, it's the caller's responsibility to delete the reader.
  28532. */
  28533. AudioFormatReader* createReaderFor (const File& audioFile);
  28534. /** Searches through the known formats to try to create a suitable reader for
  28535. this stream.
  28536. The stream object that is passed-in will be deleted by this method or by the
  28537. reader that is returned, so the caller should not keep any references to it.
  28538. The stream that is passed-in must be capable of being repositioned so
  28539. that all the formats can have a go at opening it.
  28540. If none of the registered formats can open the stream, it'll return 0. If it
  28541. returns a reader, it's the caller's responsibility to delete the reader.
  28542. */
  28543. AudioFormatReader* createReaderFor (InputStream* audioFileStream);
  28544. private:
  28545. OwnedArray<AudioFormat> knownFormats;
  28546. int defaultFormatIndex;
  28547. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatManager);
  28548. };
  28549. #endif // __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  28550. /*** End of inlined file: juce_AudioFormatManager.h ***/
  28551. #endif
  28552. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  28553. #endif
  28554. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  28555. #endif
  28556. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28557. /*** Start of inlined file: juce_AudioSubsectionReader.h ***/
  28558. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28559. #define __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28560. /**
  28561. This class is used to wrap an AudioFormatReader and only read from a
  28562. subsection of the file.
  28563. So if you have a reader which can read a 1000 sample file, you could wrap it
  28564. in one of these to only access, e.g. samples 100 to 200, and any samples
  28565. outside that will come back as 0. Accessing sample 0 from this reader will
  28566. actually read the first sample from the other's subsection, which might
  28567. be at a non-zero position.
  28568. @see AudioFormatReader
  28569. */
  28570. class JUCE_API AudioSubsectionReader : public AudioFormatReader
  28571. {
  28572. public:
  28573. /** Creates a AudioSubsectionReader for a given data source.
  28574. @param sourceReader the source reader from which we'll be taking data
  28575. @param subsectionStartSample the sample within the source reader which will be
  28576. mapped onto sample 0 for this reader.
  28577. @param subsectionLength the number of samples from the source that will
  28578. make up the subsection. If this reader is asked for
  28579. any samples beyond this region, it will return zero.
  28580. @param deleteSourceWhenDeleted if true, the sourceReader object will be deleted when
  28581. this object is deleted.
  28582. */
  28583. AudioSubsectionReader (AudioFormatReader* sourceReader,
  28584. int64 subsectionStartSample,
  28585. int64 subsectionLength,
  28586. bool deleteSourceWhenDeleted);
  28587. /** Destructor. */
  28588. ~AudioSubsectionReader();
  28589. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  28590. int64 startSampleInFile, int numSamples);
  28591. void readMaxLevels (int64 startSample,
  28592. int64 numSamples,
  28593. float& lowestLeft,
  28594. float& highestLeft,
  28595. float& lowestRight,
  28596. float& highestRight);
  28597. private:
  28598. AudioFormatReader* const source;
  28599. int64 startSample, length;
  28600. const bool deleteSourceWhenDeleted;
  28601. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioSubsectionReader);
  28602. };
  28603. #endif // __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28604. /*** End of inlined file: juce_AudioSubsectionReader.h ***/
  28605. #endif
  28606. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28607. /*** Start of inlined file: juce_AudioThumbnail.h ***/
  28608. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28609. #define __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28610. class AudioThumbnailCache;
  28611. /**
  28612. Makes it easy to quickly draw scaled views of the waveform shape of an
  28613. audio file.
  28614. To use this class, just create an AudioThumbNail class for the file you want
  28615. to draw, call setSource to tell it which file or resource to use, then call
  28616. drawChannel() to draw it.
  28617. The class will asynchronously scan the wavefile to create its scaled-down view,
  28618. so you should make your UI repaint itself as this data comes in. To do this, the
  28619. AudioThumbnail is a ChangeBroadcaster, and will broadcast a message when its
  28620. listeners should repaint themselves.
  28621. The thumbnail stores an internal low-res version of the wave data, and this can
  28622. be loaded and saved to avoid having to scan the file again.
  28623. @see AudioThumbnailCache
  28624. */
  28625. class JUCE_API AudioThumbnail : public ChangeBroadcaster
  28626. {
  28627. public:
  28628. /** Creates an audio thumbnail.
  28629. @param sourceSamplesPerThumbnailSample when creating a stored, low-res version
  28630. of the audio data, this is the scale at which it should be done. (This
  28631. number is the number of original samples that will be averaged for each
  28632. low-res sample)
  28633. @param formatManagerToUse the audio format manager that is used to open the file
  28634. @param cacheToUse an instance of an AudioThumbnailCache - this provides a background
  28635. thread and storage that is used to by the thumbnail, and the cache
  28636. object can be shared between multiple thumbnails
  28637. */
  28638. AudioThumbnail (int sourceSamplesPerThumbnailSample,
  28639. AudioFormatManager& formatManagerToUse,
  28640. AudioThumbnailCache& cacheToUse);
  28641. /** Destructor. */
  28642. ~AudioThumbnail();
  28643. /** Clears and resets the thumbnail. */
  28644. void clear();
  28645. /** Specifies the file or stream that contains the audio file.
  28646. For a file, just call
  28647. @code
  28648. setSource (new FileInputSource (file))
  28649. @endcode
  28650. You can pass a zero in here to clear the thumbnail.
  28651. The source that is passed in will be deleted by this object when it is no longer needed.
  28652. @returns true if the source could be opened as a valid audio file, false if this failed for
  28653. some reason.
  28654. */
  28655. bool setSource (InputSource* newSource);
  28656. /** Gives the thumbnail an AudioFormatReader to use directly.
  28657. This will start parsing the audio in a background thread (unless the hash code
  28658. can be looked-up successfully in the thumbnail cache). Note that the reader
  28659. object will be held by the thumbnail and deleted later when no longer needed.
  28660. The thumbnail will actually keep hold of this reader until you clear the thumbnail
  28661. or change the input source, so the file will be held open for all this time. If
  28662. you don't want the thumbnail to keep a file handle open continuously, you
  28663. should use the setSource() method instead, which will only open the file when
  28664. it needs to.
  28665. */
  28666. void setReader (AudioFormatReader* newReader, int64 hashCode);
  28667. /** Resets the thumbnail, ready for adding data with the specified format.
  28668. If you're going to generate a thumbnail yourself, call this before using addBlock()
  28669. to add the data.
  28670. */
  28671. void reset (int numChannels, double sampleRate, int64 totalSamplesInSource = 0);
  28672. /** Adds a block of level data to the thumbnail.
  28673. Call reset() before using this, to tell the thumbnail about the data format.
  28674. */
  28675. void addBlock (int64 sampleNumberInSource, const AudioSampleBuffer& newData,
  28676. int startOffsetInBuffer, int numSamples);
  28677. /** Reloads the low res thumbnail data from an input stream.
  28678. This is not an audio file stream! It takes a stream of thumbnail data that would
  28679. previously have been created by the saveTo() method.
  28680. @see saveTo
  28681. */
  28682. void loadFrom (InputStream& input);
  28683. /** Saves the low res thumbnail data to an output stream.
  28684. The data that is written can later be reloaded using loadFrom().
  28685. @see loadFrom
  28686. */
  28687. void saveTo (OutputStream& output) const;
  28688. /** Returns the number of channels in the file. */
  28689. int getNumChannels() const noexcept;
  28690. /** Returns the length of the audio file, in seconds. */
  28691. double getTotalLength() const noexcept;
  28692. /** Draws the waveform for a channel.
  28693. The waveform will be drawn within the specified rectangle, where startTime
  28694. and endTime specify the times within the audio file that should be positioned
  28695. at the left and right edges of the rectangle.
  28696. The waveform will be scaled vertically so that a full-volume sample will fill
  28697. the rectangle vertically, but you can also specify an extra vertical scale factor
  28698. with the verticalZoomFactor parameter.
  28699. */
  28700. void drawChannel (Graphics& g,
  28701. const Rectangle<int>& area,
  28702. double startTimeSeconds,
  28703. double endTimeSeconds,
  28704. int channelNum,
  28705. float verticalZoomFactor);
  28706. /** Draws the waveforms for all channels in the thumbnail.
  28707. This will call drawChannel() to render each of the thumbnail's channels, stacked
  28708. above each other within the specified area.
  28709. @see drawChannel
  28710. */
  28711. void drawChannels (Graphics& g,
  28712. const Rectangle<int>& area,
  28713. double startTimeSeconds,
  28714. double endTimeSeconds,
  28715. float verticalZoomFactor);
  28716. /** Returns true if the low res preview is fully generated. */
  28717. bool isFullyLoaded() const noexcept;
  28718. /** Returns the number of samples that have been set in the thumbnail. */
  28719. int64 getNumSamplesFinished() const noexcept;
  28720. /** Returns the highest level in the thumbnail.
  28721. Note that because the thumb only stores low-resolution data, this isn't
  28722. an accurate representation of the highest value, it's only a rough approximation.
  28723. */
  28724. float getApproximatePeak() const;
  28725. /** Reads the approximate min and max levels from a section of the thumbnail.
  28726. The lowest and highest samples are returned in minValue and maxValue, but obviously
  28727. because the thumb only stores low-resolution data, these numbers will only be a rough
  28728. approximation of the true values.
  28729. */
  28730. void getApproximateMinMax (double startTime, double endTime, int channelIndex,
  28731. float& minValue, float& maxValue) const noexcept;
  28732. /** Returns the hash code that was set by setSource() or setReader(). */
  28733. int64 getHashCode() const;
  28734. #ifndef DOXYGEN
  28735. class LevelDataSource; // (this is only public to avoid a VC6 bug)
  28736. #endif
  28737. private:
  28738. AudioFormatManager& formatManagerToUse;
  28739. AudioThumbnailCache& cache;
  28740. struct MinMaxValue;
  28741. class ThumbData;
  28742. class CachedWindow;
  28743. friend class LevelDataSource;
  28744. friend class ScopedPointer<LevelDataSource>;
  28745. friend class ThumbData;
  28746. friend class OwnedArray<ThumbData>;
  28747. friend class CachedWindow;
  28748. friend class ScopedPointer<CachedWindow>;
  28749. ScopedPointer<LevelDataSource> source;
  28750. ScopedPointer<CachedWindow> window;
  28751. OwnedArray<ThumbData> channels;
  28752. int32 samplesPerThumbSample;
  28753. int64 totalSamples, numSamplesFinished;
  28754. int32 numChannels;
  28755. double sampleRate;
  28756. CriticalSection lock;
  28757. void clearChannelData();
  28758. bool setDataSource (LevelDataSource* newSource);
  28759. void setLevels (const MinMaxValue* const* values, int thumbIndex, int numChans, int numValues);
  28760. void createChannels (int length);
  28761. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioThumbnail);
  28762. };
  28763. #endif // __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28764. /*** End of inlined file: juce_AudioThumbnail.h ***/
  28765. #endif
  28766. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28767. /*** Start of inlined file: juce_AudioThumbnailCache.h ***/
  28768. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28769. #define __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28770. struct ThumbnailCacheEntry;
  28771. /**
  28772. An instance of this class is used to manage multiple AudioThumbnail objects.
  28773. The cache runs a single background thread that is shared by all the thumbnails
  28774. that need it, and it maintains a set of low-res previews in memory, to avoid
  28775. having to re-scan audio files too often.
  28776. @see AudioThumbnail
  28777. */
  28778. class JUCE_API AudioThumbnailCache : public TimeSliceThread
  28779. {
  28780. public:
  28781. /** Creates a cache object.
  28782. The maxNumThumbsToStore parameter lets you specify how many previews should
  28783. be kept in memory at once.
  28784. */
  28785. explicit AudioThumbnailCache (int maxNumThumbsToStore);
  28786. /** Destructor. */
  28787. ~AudioThumbnailCache();
  28788. /** Clears out any stored thumbnails.
  28789. */
  28790. void clear();
  28791. /** Reloads the specified thumb if this cache contains the appropriate stored
  28792. data.
  28793. This is called automatically by the AudioThumbnail class, so you shouldn't
  28794. normally need to call it directly.
  28795. */
  28796. bool loadThumb (AudioThumbnail& thumb, int64 hashCode);
  28797. /** Stores the cachable data from the specified thumb in this cache.
  28798. This is called automatically by the AudioThumbnail class, so you shouldn't
  28799. normally need to call it directly.
  28800. */
  28801. void storeThumb (const AudioThumbnail& thumb, int64 hashCode);
  28802. private:
  28803. OwnedArray <ThumbnailCacheEntry> thumbs;
  28804. int maxNumThumbsToStore;
  28805. ThumbnailCacheEntry* findThumbFor (int64 hash) const;
  28806. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioThumbnailCache);
  28807. };
  28808. #endif // __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28809. /*** End of inlined file: juce_AudioThumbnailCache.h ***/
  28810. #endif
  28811. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28812. /*** Start of inlined file: juce_FlacAudioFormat.h ***/
  28813. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28814. #define __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28815. #if JUCE_USE_FLAC || defined (DOXYGEN)
  28816. /**
  28817. Reads and writes the lossless-compression FLAC audio format.
  28818. To compile this, you'll need to set the JUCE_USE_FLAC flag in juce_Config.h,
  28819. and make sure your include search path and library search path are set up to find
  28820. the FLAC header files and static libraries.
  28821. @see AudioFormat
  28822. */
  28823. class JUCE_API FlacAudioFormat : public AudioFormat
  28824. {
  28825. public:
  28826. FlacAudioFormat();
  28827. ~FlacAudioFormat();
  28828. const Array <int> getPossibleSampleRates();
  28829. const Array <int> getPossibleBitDepths();
  28830. bool canDoStereo();
  28831. bool canDoMono();
  28832. bool isCompressed();
  28833. StringArray getQualityOptions();
  28834. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28835. bool deleteStreamIfOpeningFails);
  28836. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28837. double sampleRateToUse,
  28838. unsigned int numberOfChannels,
  28839. int bitsPerSample,
  28840. const StringPairArray& metadataValues,
  28841. int qualityOptionIndex);
  28842. private:
  28843. JUCE_LEAK_DETECTOR (FlacAudioFormat);
  28844. };
  28845. #endif
  28846. #endif // __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28847. /*** End of inlined file: juce_FlacAudioFormat.h ***/
  28848. #endif
  28849. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28850. /*** Start of inlined file: juce_OggVorbisAudioFormat.h ***/
  28851. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28852. #define __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28853. #if JUCE_USE_OGGVORBIS || defined (DOXYGEN)
  28854. /**
  28855. Reads and writes the Ogg-Vorbis audio format.
  28856. To compile this, you'll need to set the JUCE_USE_OGGVORBIS flag in juce_Config.h,
  28857. and make sure your include search path and library search path are set up to find
  28858. the Vorbis and Ogg header files and static libraries.
  28859. @see AudioFormat,
  28860. */
  28861. class JUCE_API OggVorbisAudioFormat : public AudioFormat
  28862. {
  28863. public:
  28864. OggVorbisAudioFormat();
  28865. ~OggVorbisAudioFormat();
  28866. const Array<int> getPossibleSampleRates();
  28867. const Array<int> getPossibleBitDepths();
  28868. bool canDoStereo();
  28869. bool canDoMono();
  28870. bool isCompressed();
  28871. StringArray getQualityOptions();
  28872. /** Tries to estimate the quality level of an ogg file based on its size.
  28873. If it can't read the file for some reason, this will just return 1 (medium quality),
  28874. otherwise it will return the approximate quality setting that would have been used
  28875. to create the file.
  28876. @see getQualityOptions
  28877. */
  28878. int estimateOggFileQuality (const File& source);
  28879. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28880. bool deleteStreamIfOpeningFails);
  28881. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28882. double sampleRateToUse,
  28883. unsigned int numberOfChannels,
  28884. int bitsPerSample,
  28885. const StringPairArray& metadataValues,
  28886. int qualityOptionIndex);
  28887. private:
  28888. JUCE_LEAK_DETECTOR (OggVorbisAudioFormat);
  28889. };
  28890. #endif
  28891. #endif // __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28892. /*** End of inlined file: juce_OggVorbisAudioFormat.h ***/
  28893. #endif
  28894. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28895. /*** Start of inlined file: juce_QuickTimeAudioFormat.h ***/
  28896. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28897. #define __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28898. #if JUCE_QUICKTIME
  28899. /**
  28900. Uses QuickTime to read the audio track a movie or media file.
  28901. As well as QuickTime movies, this should also manage to open other audio
  28902. files that quicktime can understand, like mp3, m4a, etc.
  28903. @see AudioFormat
  28904. */
  28905. class JUCE_API QuickTimeAudioFormat : public AudioFormat
  28906. {
  28907. public:
  28908. /** Creates a format object. */
  28909. QuickTimeAudioFormat();
  28910. /** Destructor. */
  28911. ~QuickTimeAudioFormat();
  28912. const Array <int> getPossibleSampleRates();
  28913. const Array <int> getPossibleBitDepths();
  28914. bool canDoStereo();
  28915. bool canDoMono();
  28916. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28917. bool deleteStreamIfOpeningFails);
  28918. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28919. double sampleRateToUse,
  28920. unsigned int numberOfChannels,
  28921. int bitsPerSample,
  28922. const StringPairArray& metadataValues,
  28923. int qualityOptionIndex);
  28924. private:
  28925. JUCE_LEAK_DETECTOR (QuickTimeAudioFormat);
  28926. };
  28927. #endif
  28928. #endif // __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28929. /*** End of inlined file: juce_QuickTimeAudioFormat.h ***/
  28930. #endif
  28931. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28932. /*** Start of inlined file: juce_WavAudioFormat.h ***/
  28933. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28934. #define __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28935. /**
  28936. Reads and Writes WAV format audio files.
  28937. @see AudioFormat
  28938. */
  28939. class JUCE_API WavAudioFormat : public AudioFormat
  28940. {
  28941. public:
  28942. /** Creates a format object. */
  28943. WavAudioFormat();
  28944. /** Destructor. */
  28945. ~WavAudioFormat();
  28946. /** Metadata property name used by wav readers and writers for adding
  28947. a BWAV chunk to the file.
  28948. @see AudioFormatReader::metadataValues, createWriterFor
  28949. */
  28950. static const char* const bwavDescription;
  28951. /** Metadata property name used by wav readers and writers for adding
  28952. a BWAV chunk to the file.
  28953. @see AudioFormatReader::metadataValues, createWriterFor
  28954. */
  28955. static const char* const bwavOriginator;
  28956. /** Metadata property name used by wav readers and writers for adding
  28957. a BWAV chunk to the file.
  28958. @see AudioFormatReader::metadataValues, createWriterFor
  28959. */
  28960. static const char* const bwavOriginatorRef;
  28961. /** Metadata property name used by wav readers and writers for adding
  28962. a BWAV chunk to the file.
  28963. Date format is: yyyy-mm-dd
  28964. @see AudioFormatReader::metadataValues, createWriterFor
  28965. */
  28966. static const char* const bwavOriginationDate;
  28967. /** Metadata property name used by wav readers and writers for adding
  28968. a BWAV chunk to the file.
  28969. Time format is: hh-mm-ss
  28970. @see AudioFormatReader::metadataValues, createWriterFor
  28971. */
  28972. static const char* const bwavOriginationTime;
  28973. /** Metadata property name used by wav readers and writers for adding
  28974. a BWAV chunk to the file.
  28975. This is the number of samples from the start of an edit that the
  28976. file is supposed to begin at. Seems like an obvious mistake to
  28977. only allow a file to occur in an edit once, but that's the way
  28978. it is..
  28979. @see AudioFormatReader::metadataValues, createWriterFor
  28980. */
  28981. static const char* const bwavTimeReference;
  28982. /** Metadata property name used by wav readers and writers for adding
  28983. a BWAV chunk to the file.
  28984. This is a
  28985. @see AudioFormatReader::metadataValues, createWriterFor
  28986. */
  28987. static const char* const bwavCodingHistory;
  28988. /** Utility function to fill out the appropriate metadata for a BWAV file.
  28989. This just makes it easier than using the property names directly, and it
  28990. fills out the time and date in the right format.
  28991. */
  28992. static StringPairArray createBWAVMetadata (const String& description,
  28993. const String& originator,
  28994. const String& originatorRef,
  28995. const Time& dateAndTime,
  28996. const int64 timeReferenceSamples,
  28997. const String& codingHistory);
  28998. const Array <int> getPossibleSampleRates();
  28999. const Array <int> getPossibleBitDepths();
  29000. bool canDoStereo();
  29001. bool canDoMono();
  29002. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  29003. bool deleteStreamIfOpeningFails);
  29004. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  29005. double sampleRateToUse,
  29006. unsigned int numberOfChannels,
  29007. int bitsPerSample,
  29008. const StringPairArray& metadataValues,
  29009. int qualityOptionIndex);
  29010. /** Utility function to replace the metadata in a wav file with a new set of values.
  29011. If possible, this cheats by overwriting just the metadata region of the file, rather
  29012. than by copying the whole file again.
  29013. */
  29014. bool replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata);
  29015. private:
  29016. JUCE_LEAK_DETECTOR (WavAudioFormat);
  29017. };
  29018. #endif // __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  29019. /*** End of inlined file: juce_WavAudioFormat.h ***/
  29020. #endif
  29021. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  29022. /*** Start of inlined file: juce_AudioFormatReaderSource.h ***/
  29023. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  29024. #define __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  29025. /*** Start of inlined file: juce_PositionableAudioSource.h ***/
  29026. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  29027. #define __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  29028. /**
  29029. A type of AudioSource which can be repositioned.
  29030. The basic AudioSource just streams continuously with no idea of a current
  29031. time or length, so the PositionableAudioSource is used for a finite stream
  29032. that has a current read position.
  29033. @see AudioSource, AudioTransportSource
  29034. */
  29035. class JUCE_API PositionableAudioSource : public AudioSource
  29036. {
  29037. protected:
  29038. /** Creates the PositionableAudioSource. */
  29039. PositionableAudioSource() noexcept {}
  29040. public:
  29041. /** Destructor */
  29042. ~PositionableAudioSource() {}
  29043. /** Tells the stream to move to a new position.
  29044. Calling this indicates that the next call to AudioSource::getNextAudioBlock()
  29045. should return samples from this position.
  29046. Note that this may be called on a different thread to getNextAudioBlock(),
  29047. so the subclass should make sure it's synchronised.
  29048. */
  29049. virtual void setNextReadPosition (int64 newPosition) = 0;
  29050. /** Returns the position from which the next block will be returned.
  29051. @see setNextReadPosition
  29052. */
  29053. virtual int64 getNextReadPosition() const = 0;
  29054. /** Returns the total length of the stream (in samples). */
  29055. virtual int64 getTotalLength() const = 0;
  29056. /** Returns true if this source is actually playing in a loop. */
  29057. virtual bool isLooping() const = 0;
  29058. /** Tells the source whether you'd like it to play in a loop. */
  29059. virtual void setLooping (bool shouldLoop) { (void) shouldLoop; }
  29060. };
  29061. #endif // __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  29062. /*** End of inlined file: juce_PositionableAudioSource.h ***/
  29063. /**
  29064. A type of AudioSource that will read from an AudioFormatReader.
  29065. @see PositionableAudioSource, AudioTransportSource, BufferingAudioSource
  29066. */
  29067. class JUCE_API AudioFormatReaderSource : public PositionableAudioSource
  29068. {
  29069. public:
  29070. /** Creates an AudioFormatReaderSource for a given reader.
  29071. @param sourceReader the reader to use as the data source - this must
  29072. not be null
  29073. @param deleteReaderWhenThisIsDeleted if true, the reader passed-in will be deleted
  29074. when this object is deleted; if false it will be
  29075. left up to the caller to manage its lifetime
  29076. */
  29077. AudioFormatReaderSource (AudioFormatReader* sourceReader,
  29078. bool deleteReaderWhenThisIsDeleted);
  29079. /** Destructor. */
  29080. ~AudioFormatReaderSource();
  29081. /** Toggles loop-mode.
  29082. If set to true, it will continuously loop the input source. If false,
  29083. it will just emit silence after the source has finished.
  29084. @see isLooping
  29085. */
  29086. void setLooping (bool shouldLoop);
  29087. /** Returns whether loop-mode is turned on or not. */
  29088. bool isLooping() const { return looping; }
  29089. /** Returns the reader that's being used. */
  29090. AudioFormatReader* getAudioFormatReader() const noexcept { return reader; }
  29091. /** Implementation of the AudioSource method. */
  29092. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29093. /** Implementation of the AudioSource method. */
  29094. void releaseResources();
  29095. /** Implementation of the AudioSource method. */
  29096. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29097. /** Implements the PositionableAudioSource method. */
  29098. void setNextReadPosition (int64 newPosition);
  29099. /** Implements the PositionableAudioSource method. */
  29100. int64 getNextReadPosition() const;
  29101. /** Implements the PositionableAudioSource method. */
  29102. int64 getTotalLength() const;
  29103. private:
  29104. OptionalScopedPointer<AudioFormatReader> reader;
  29105. int64 volatile nextPlayPos;
  29106. bool volatile looping;
  29107. void readBufferSection (int start, int length, AudioSampleBuffer& buffer, int startSample);
  29108. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatReaderSource);
  29109. };
  29110. #endif // __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  29111. /*** End of inlined file: juce_AudioFormatReaderSource.h ***/
  29112. #endif
  29113. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  29114. #endif
  29115. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  29116. /*** Start of inlined file: juce_AudioSourcePlayer.h ***/
  29117. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  29118. #define __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  29119. /*** Start of inlined file: juce_AudioIODevice.h ***/
  29120. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  29121. #define __JUCE_AUDIOIODEVICE_JUCEHEADER__
  29122. class AudioIODevice;
  29123. /**
  29124. One of these is passed to an AudioIODevice object to stream the audio data
  29125. in and out.
  29126. The AudioIODevice will repeatedly call this class's audioDeviceIOCallback()
  29127. method on its own high-priority audio thread, when it needs to send or receive
  29128. the next block of data.
  29129. @see AudioIODevice, AudioDeviceManager
  29130. */
  29131. class JUCE_API AudioIODeviceCallback
  29132. {
  29133. public:
  29134. /** Destructor. */
  29135. virtual ~AudioIODeviceCallback() {}
  29136. /** Processes a block of incoming and outgoing audio data.
  29137. The subclass's implementation should use the incoming audio for whatever
  29138. purposes it needs to, and must fill all the output channels with the next
  29139. block of output data before returning.
  29140. The channel data is arranged with the same array indices as the channel name
  29141. array returned by AudioIODevice::getOutputChannelNames(), but those channels
  29142. that aren't specified in AudioIODevice::open() will have a null pointer for their
  29143. associated channel, so remember to check for this.
  29144. @param inputChannelData a set of arrays containing the audio data for each
  29145. incoming channel - this data is valid until the function
  29146. returns. There will be one channel of data for each input
  29147. channel that was enabled when the audio device was opened
  29148. (see AudioIODevice::open())
  29149. @param numInputChannels the number of pointers to channel data in the
  29150. inputChannelData array.
  29151. @param outputChannelData a set of arrays which need to be filled with the data
  29152. that should be sent to each outgoing channel of the device.
  29153. There will be one channel of data for each output channel
  29154. that was enabled when the audio device was opened (see
  29155. AudioIODevice::open())
  29156. The initial contents of the array is undefined, so the
  29157. callback function must fill all the channels with zeros if
  29158. its output is silence. Failing to do this could cause quite
  29159. an unpleasant noise!
  29160. @param numOutputChannels the number of pointers to channel data in the
  29161. outputChannelData array.
  29162. @param numSamples the number of samples in each channel of the input and
  29163. output arrays. The number of samples will depend on the
  29164. audio device's buffer size and will usually remain constant,
  29165. although this isn't guaranteed, so make sure your code can
  29166. cope with reasonable changes in the buffer size from one
  29167. callback to the next.
  29168. */
  29169. virtual void audioDeviceIOCallback (const float** inputChannelData,
  29170. int numInputChannels,
  29171. float** outputChannelData,
  29172. int numOutputChannels,
  29173. int numSamples) = 0;
  29174. /** Called to indicate that the device is about to start calling back.
  29175. This will be called just before the audio callbacks begin, either when this
  29176. callback has just been added to an audio device, or after the device has been
  29177. restarted because of a sample-rate or block-size change.
  29178. You can use this opportunity to find out the sample rate and block size
  29179. that the device is going to use by calling the AudioIODevice::getCurrentSampleRate()
  29180. and AudioIODevice::getCurrentBufferSizeSamples() on the supplied pointer.
  29181. @param device the audio IO device that will be used to drive the callback.
  29182. Note that if you're going to store this this pointer, it is
  29183. only valid until the next time that audioDeviceStopped is called.
  29184. */
  29185. virtual void audioDeviceAboutToStart (AudioIODevice* device) = 0;
  29186. /** Called to indicate that the device has stopped. */
  29187. virtual void audioDeviceStopped() = 0;
  29188. /** This can be overridden to be told if the device generates an error while operating.
  29189. Be aware that this could be called by any thread! And not all devices perform
  29190. this callback.
  29191. */
  29192. virtual void audioDeviceError (const String& errorMessage);
  29193. };
  29194. /**
  29195. Base class for an audio device with synchronised input and output channels.
  29196. Subclasses of this are used to implement different protocols such as DirectSound,
  29197. ASIO, CoreAudio, etc.
  29198. To create one of these, you'll need to use the AudioIODeviceType class - see the
  29199. documentation for that class for more info.
  29200. For an easier way of managing audio devices and their settings, have a look at the
  29201. AudioDeviceManager class.
  29202. @see AudioIODeviceType, AudioDeviceManager
  29203. */
  29204. class JUCE_API AudioIODevice
  29205. {
  29206. public:
  29207. /** Destructor. */
  29208. virtual ~AudioIODevice();
  29209. /** Returns the device's name, (as set in the constructor). */
  29210. const String& getName() const noexcept { return name; }
  29211. /** Returns the type of the device.
  29212. E.g. "CoreAudio", "ASIO", etc. - this comes from the AudioIODeviceType that created it.
  29213. */
  29214. const String& getTypeName() const noexcept { return typeName; }
  29215. /** Returns the names of all the available output channels on this device.
  29216. To find out which of these are currently in use, call getActiveOutputChannels().
  29217. */
  29218. virtual StringArray getOutputChannelNames() = 0;
  29219. /** Returns the names of all the available input channels on this device.
  29220. To find out which of these are currently in use, call getActiveInputChannels().
  29221. */
  29222. virtual StringArray getInputChannelNames() = 0;
  29223. /** Returns the number of sample-rates this device supports.
  29224. To find out which rates are available on this device, use this method to
  29225. find out how many there are, and getSampleRate() to get the rates.
  29226. @see getSampleRate
  29227. */
  29228. virtual int getNumSampleRates() = 0;
  29229. /** Returns one of the sample-rates this device supports.
  29230. To find out which rates are available on this device, use getNumSampleRates() to
  29231. find out how many there are, and getSampleRate() to get the individual rates.
  29232. The sample rate is set by the open() method.
  29233. (Note that for DirectSound some rates might not work, depending on combinations
  29234. of i/o channels that are being opened).
  29235. @see getNumSampleRates
  29236. */
  29237. virtual double getSampleRate (int index) = 0;
  29238. /** Returns the number of sizes of buffer that are available.
  29239. @see getBufferSizeSamples, getDefaultBufferSize
  29240. */
  29241. virtual int getNumBufferSizesAvailable() = 0;
  29242. /** Returns one of the possible buffer-sizes.
  29243. @param index the index of the buffer-size to use, from 0 to getNumBufferSizesAvailable() - 1
  29244. @returns a number of samples
  29245. @see getNumBufferSizesAvailable, getDefaultBufferSize
  29246. */
  29247. virtual int getBufferSizeSamples (int index) = 0;
  29248. /** Returns the default buffer-size to use.
  29249. @returns a number of samples
  29250. @see getNumBufferSizesAvailable, getBufferSizeSamples
  29251. */
  29252. virtual int getDefaultBufferSize() = 0;
  29253. /** Tries to open the device ready to play.
  29254. @param inputChannels a BigInteger in which a set bit indicates that the corresponding
  29255. input channel should be enabled
  29256. @param outputChannels a BigInteger in which a set bit indicates that the corresponding
  29257. output channel should be enabled
  29258. @param sampleRate the sample rate to try to use - to find out which rates are
  29259. available, see getNumSampleRates() and getSampleRate()
  29260. @param bufferSizeSamples the size of i/o buffer to use - to find out the available buffer
  29261. sizes, see getNumBufferSizesAvailable() and getBufferSizeSamples()
  29262. @returns an error description if there's a problem, or an empty string if it succeeds in
  29263. opening the device
  29264. @see close
  29265. */
  29266. virtual const String open (const BigInteger& inputChannels,
  29267. const BigInteger& outputChannels,
  29268. double sampleRate,
  29269. int bufferSizeSamples) = 0;
  29270. /** Closes and releases the device if it's open. */
  29271. virtual void close() = 0;
  29272. /** Returns true if the device is still open.
  29273. A device might spontaneously close itself if something goes wrong, so this checks if
  29274. it's still open.
  29275. */
  29276. virtual bool isOpen() = 0;
  29277. /** Starts the device actually playing.
  29278. This must be called after the device has been opened.
  29279. @param callback the callback to use for streaming the data.
  29280. @see AudioIODeviceCallback, open
  29281. */
  29282. virtual void start (AudioIODeviceCallback* callback) = 0;
  29283. /** Stops the device playing.
  29284. Once a device has been started, this will stop it. Any pending calls to the
  29285. callback class will be flushed before this method returns.
  29286. */
  29287. virtual void stop() = 0;
  29288. /** Returns true if the device is still calling back.
  29289. The device might mysteriously stop, so this checks whether it's
  29290. still playing.
  29291. */
  29292. virtual bool isPlaying() = 0;
  29293. /** Returns the last error that happened if anything went wrong. */
  29294. virtual const String getLastError() = 0;
  29295. /** Returns the buffer size that the device is currently using.
  29296. If the device isn't actually open, this value doesn't really mean much.
  29297. */
  29298. virtual int getCurrentBufferSizeSamples() = 0;
  29299. /** Returns the sample rate that the device is currently using.
  29300. If the device isn't actually open, this value doesn't really mean much.
  29301. */
  29302. virtual double getCurrentSampleRate() = 0;
  29303. /** Returns the device's current physical bit-depth.
  29304. If the device isn't actually open, this value doesn't really mean much.
  29305. */
  29306. virtual int getCurrentBitDepth() = 0;
  29307. /** Returns a mask showing which of the available output channels are currently
  29308. enabled.
  29309. @see getOutputChannelNames
  29310. */
  29311. virtual const BigInteger getActiveOutputChannels() const = 0;
  29312. /** Returns a mask showing which of the available input channels are currently
  29313. enabled.
  29314. @see getInputChannelNames
  29315. */
  29316. virtual const BigInteger getActiveInputChannels() const = 0;
  29317. /** Returns the device's output latency.
  29318. This is the delay in samples between a callback getting a block of data, and
  29319. that data actually getting played.
  29320. */
  29321. virtual int getOutputLatencyInSamples() = 0;
  29322. /** Returns the device's input latency.
  29323. This is the delay in samples between some audio actually arriving at the soundcard,
  29324. and the callback getting passed this block of data.
  29325. */
  29326. virtual int getInputLatencyInSamples() = 0;
  29327. /** True if this device can show a pop-up control panel for editing its settings.
  29328. This is generally just true of ASIO devices. If true, you can call showControlPanel()
  29329. to display it.
  29330. */
  29331. virtual bool hasControlPanel() const;
  29332. /** Shows a device-specific control panel if there is one.
  29333. This should only be called for devices which return true from hasControlPanel().
  29334. */
  29335. virtual bool showControlPanel();
  29336. protected:
  29337. /** Creates a device, setting its name and type member variables. */
  29338. AudioIODevice (const String& deviceName,
  29339. const String& typeName);
  29340. /** @internal */
  29341. String name, typeName;
  29342. };
  29343. #endif // __JUCE_AUDIOIODEVICE_JUCEHEADER__
  29344. /*** End of inlined file: juce_AudioIODevice.h ***/
  29345. /**
  29346. Wrapper class to continuously stream audio from an audio source to an
  29347. AudioIODevice.
  29348. This object acts as an AudioIODeviceCallback, so can be attached to an
  29349. output device, and will stream audio from an AudioSource.
  29350. */
  29351. class JUCE_API AudioSourcePlayer : public AudioIODeviceCallback
  29352. {
  29353. public:
  29354. /** Creates an empty AudioSourcePlayer. */
  29355. AudioSourcePlayer();
  29356. /** Destructor.
  29357. Make sure this object isn't still being used by an AudioIODevice before
  29358. deleting it!
  29359. */
  29360. virtual ~AudioSourcePlayer();
  29361. /** Changes the current audio source to play from.
  29362. If the source passed in is already being used, this method will do nothing.
  29363. If the source is not null, its prepareToPlay() method will be called
  29364. before it starts being used for playback.
  29365. If there's another source currently playing, its releaseResources() method
  29366. will be called after it has been swapped for the new one.
  29367. @param newSource the new source to use - this will NOT be deleted
  29368. by this object when no longer needed, so it's the
  29369. caller's responsibility to manage it.
  29370. */
  29371. void setSource (AudioSource* newSource);
  29372. /** Returns the source that's playing.
  29373. May return 0 if there's no source.
  29374. */
  29375. AudioSource* getCurrentSource() const noexcept { return source; }
  29376. /** Sets a gain to apply to the audio data.
  29377. @see getGain
  29378. */
  29379. void setGain (float newGain) noexcept;
  29380. /** Returns the current gain.
  29381. @see setGain
  29382. */
  29383. float getGain() const noexcept { return gain; }
  29384. /** Implementation of the AudioIODeviceCallback method. */
  29385. void audioDeviceIOCallback (const float** inputChannelData,
  29386. int totalNumInputChannels,
  29387. float** outputChannelData,
  29388. int totalNumOutputChannels,
  29389. int numSamples);
  29390. /** Implementation of the AudioIODeviceCallback method. */
  29391. void audioDeviceAboutToStart (AudioIODevice* device);
  29392. /** Implementation of the AudioIODeviceCallback method. */
  29393. void audioDeviceStopped();
  29394. private:
  29395. CriticalSection readLock;
  29396. AudioSource* source;
  29397. double sampleRate;
  29398. int bufferSize;
  29399. float* channels [128];
  29400. float* outputChans [128];
  29401. const float* inputChans [128];
  29402. AudioSampleBuffer tempBuffer;
  29403. float lastGain, gain;
  29404. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioSourcePlayer);
  29405. };
  29406. #endif // __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  29407. /*** End of inlined file: juce_AudioSourcePlayer.h ***/
  29408. #endif
  29409. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  29410. /*** Start of inlined file: juce_AudioTransportSource.h ***/
  29411. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  29412. #define __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  29413. /*** Start of inlined file: juce_BufferingAudioSource.h ***/
  29414. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  29415. #define __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  29416. /**
  29417. An AudioSource which takes another source as input, and buffers it using a thread.
  29418. Create this as a wrapper around another thread, and it will read-ahead with
  29419. a background thread to smooth out playback. You can either create one of these
  29420. directly, or use it indirectly using an AudioTransportSource.
  29421. @see PositionableAudioSource, AudioTransportSource
  29422. */
  29423. class JUCE_API BufferingAudioSource : public PositionableAudioSource
  29424. {
  29425. public:
  29426. /** Creates a BufferingAudioSource.
  29427. @param source the input source to read from
  29428. @param deleteSourceWhenDeleted if true, then the input source object will
  29429. be deleted when this object is deleted
  29430. @param numberOfSamplesToBuffer the size of buffer to use for reading ahead
  29431. @param numberOfChannels the number of channels that will be played
  29432. */
  29433. BufferingAudioSource (PositionableAudioSource* source,
  29434. bool deleteSourceWhenDeleted,
  29435. int numberOfSamplesToBuffer,
  29436. int numberOfChannels = 2);
  29437. /** Destructor.
  29438. The input source may be deleted depending on whether the deleteSourceWhenDeleted
  29439. flag was set in the constructor.
  29440. */
  29441. ~BufferingAudioSource();
  29442. /** Implementation of the AudioSource method. */
  29443. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29444. /** Implementation of the AudioSource method. */
  29445. void releaseResources();
  29446. /** Implementation of the AudioSource method. */
  29447. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29448. /** Implements the PositionableAudioSource method. */
  29449. void setNextReadPosition (int64 newPosition);
  29450. /** Implements the PositionableAudioSource method. */
  29451. int64 getNextReadPosition() const;
  29452. /** Implements the PositionableAudioSource method. */
  29453. int64 getTotalLength() const { return source->getTotalLength(); }
  29454. /** Implements the PositionableAudioSource method. */
  29455. bool isLooping() const { return source->isLooping(); }
  29456. private:
  29457. OptionalScopedPointer<PositionableAudioSource> source;
  29458. int numberOfSamplesToBuffer, numberOfChannels;
  29459. AudioSampleBuffer buffer;
  29460. CriticalSection bufferStartPosLock;
  29461. int64 volatile bufferValidStart, bufferValidEnd, nextPlayPos;
  29462. double volatile sampleRate;
  29463. bool wasSourceLooping;
  29464. friend class SharedBufferingAudioSourceThread;
  29465. bool readNextBufferChunk();
  29466. void readBufferSection (int64 start, int length, int bufferOffset);
  29467. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BufferingAudioSource);
  29468. };
  29469. #endif // __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  29470. /*** End of inlined file: juce_BufferingAudioSource.h ***/
  29471. /*** Start of inlined file: juce_ResamplingAudioSource.h ***/
  29472. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  29473. #define __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  29474. /**
  29475. A type of AudioSource that takes an input source and changes its sample rate.
  29476. @see AudioSource
  29477. */
  29478. class JUCE_API ResamplingAudioSource : public AudioSource
  29479. {
  29480. public:
  29481. /** Creates a ResamplingAudioSource for a given input source.
  29482. @param inputSource the input source to read from
  29483. @param deleteInputWhenDeleted if true, the input source will be deleted when
  29484. this object is deleted
  29485. @param numChannels the number of channels to process
  29486. */
  29487. ResamplingAudioSource (AudioSource* inputSource,
  29488. bool deleteInputWhenDeleted,
  29489. int numChannels = 2);
  29490. /** Destructor. */
  29491. ~ResamplingAudioSource();
  29492. /** Changes the resampling ratio.
  29493. (This value can be changed at any time, even while the source is running).
  29494. @param samplesInPerOutputSample if set to 1.0, the input is passed through; higher
  29495. values will speed it up; lower values will slow it
  29496. down. The ratio must be greater than 0
  29497. */
  29498. void setResamplingRatio (double samplesInPerOutputSample);
  29499. /** Returns the current resampling ratio.
  29500. This is the value that was set by setResamplingRatio().
  29501. */
  29502. double getResamplingRatio() const noexcept { return ratio; }
  29503. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29504. void releaseResources();
  29505. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29506. private:
  29507. OptionalScopedPointer<AudioSource> input;
  29508. double ratio, lastRatio;
  29509. AudioSampleBuffer buffer;
  29510. int bufferPos, sampsInBuffer;
  29511. double subSampleOffset;
  29512. double coefficients[6];
  29513. SpinLock ratioLock;
  29514. const int numChannels;
  29515. HeapBlock<float*> destBuffers, srcBuffers;
  29516. void setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6);
  29517. void createLowPass (double proportionalRate);
  29518. struct FilterState
  29519. {
  29520. double x1, x2, y1, y2;
  29521. };
  29522. HeapBlock<FilterState> filterStates;
  29523. void resetFilters();
  29524. void applyFilter (float* samples, int num, FilterState& fs);
  29525. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResamplingAudioSource);
  29526. };
  29527. #endif // __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  29528. /*** End of inlined file: juce_ResamplingAudioSource.h ***/
  29529. /**
  29530. An AudioSource that takes a PositionableAudioSource and allows it to be
  29531. played, stopped, started, etc.
  29532. This can also be told use a buffer and background thread to read ahead, and
  29533. if can correct for different sample-rates.
  29534. You may want to use one of these along with an AudioSourcePlayer and AudioIODevice
  29535. to control playback of an audio file.
  29536. @see AudioSource, AudioSourcePlayer
  29537. */
  29538. class JUCE_API AudioTransportSource : public PositionableAudioSource,
  29539. public ChangeBroadcaster
  29540. {
  29541. public:
  29542. /** Creates an AudioTransportSource.
  29543. After creating one of these, use the setSource() method to select an input source.
  29544. */
  29545. AudioTransportSource();
  29546. /** Destructor. */
  29547. ~AudioTransportSource();
  29548. /** Sets the reader that is being used as the input source.
  29549. This will stop playback, reset the position to 0 and change to the new reader.
  29550. The source passed in will not be deleted by this object, so must be managed by
  29551. the caller.
  29552. @param newSource the new input source to use. This may be zero
  29553. @param readAheadBufferSize a size of buffer to use for reading ahead. If this
  29554. is zero, no reading ahead will be done; if it's
  29555. greater than zero, a BufferingAudioSource will be used
  29556. to do the reading-ahead
  29557. @param sourceSampleRateToCorrectFor if this is non-zero, it specifies the sample
  29558. rate of the source, and playback will be sample-rate
  29559. adjusted to maintain playback at the correct pitch. If
  29560. this is 0, no sample-rate adjustment will be performed
  29561. @param maxNumChannels the maximum number of channels that may need to be played
  29562. */
  29563. void setSource (PositionableAudioSource* newSource,
  29564. int readAheadBufferSize = 0,
  29565. double sourceSampleRateToCorrectFor = 0.0,
  29566. int maxNumChannels = 2);
  29567. /** Changes the current playback position in the source stream.
  29568. The next time the getNextAudioBlock() method is called, this
  29569. is the time from which it'll read data.
  29570. @see getPosition
  29571. */
  29572. void setPosition (double newPosition);
  29573. /** Returns the position that the next data block will be read from
  29574. This is a time in seconds.
  29575. */
  29576. double getCurrentPosition() const;
  29577. /** Returns the stream's length in seconds. */
  29578. double getLengthInSeconds() const;
  29579. /** Returns true if the player has stopped because its input stream ran out of data.
  29580. */
  29581. bool hasStreamFinished() const noexcept { return inputStreamEOF; }
  29582. /** Starts playing (if a source has been selected).
  29583. If it starts playing, this will send a message to any ChangeListeners
  29584. that are registered with this object.
  29585. */
  29586. void start();
  29587. /** Stops playing.
  29588. If it's actually playing, this will send a message to any ChangeListeners
  29589. that are registered with this object.
  29590. */
  29591. void stop();
  29592. /** Returns true if it's currently playing. */
  29593. bool isPlaying() const noexcept { return playing; }
  29594. /** Changes the gain to apply to the output.
  29595. @param newGain a factor by which to multiply the outgoing samples,
  29596. so 1.0 = 0dB, 0.5 = -6dB, 2.0 = 6dB, etc.
  29597. */
  29598. void setGain (float newGain) noexcept;
  29599. /** Returns the current gain setting.
  29600. @see setGain
  29601. */
  29602. float getGain() const noexcept { return gain; }
  29603. /** Implementation of the AudioSource method. */
  29604. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29605. /** Implementation of the AudioSource method. */
  29606. void releaseResources();
  29607. /** Implementation of the AudioSource method. */
  29608. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29609. /** Implements the PositionableAudioSource method. */
  29610. void setNextReadPosition (int64 newPosition);
  29611. /** Implements the PositionableAudioSource method. */
  29612. int64 getNextReadPosition() const;
  29613. /** Implements the PositionableAudioSource method. */
  29614. int64 getTotalLength() const;
  29615. /** Implements the PositionableAudioSource method. */
  29616. bool isLooping() const;
  29617. private:
  29618. PositionableAudioSource* source;
  29619. ResamplingAudioSource* resamplerSource;
  29620. BufferingAudioSource* bufferingSource;
  29621. PositionableAudioSource* positionableSource;
  29622. AudioSource* masterSource;
  29623. CriticalSection callbackLock;
  29624. float volatile gain, lastGain;
  29625. bool volatile playing, stopped;
  29626. double sampleRate, sourceSampleRate;
  29627. int blockSize, readAheadBufferSize;
  29628. bool isPrepared, inputStreamEOF;
  29629. void releaseMasterResources();
  29630. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioTransportSource);
  29631. };
  29632. #endif // __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  29633. /*** End of inlined file: juce_AudioTransportSource.h ***/
  29634. #endif
  29635. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  29636. #endif
  29637. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  29638. /*** Start of inlined file: juce_ChannelRemappingAudioSource.h ***/
  29639. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  29640. #define __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  29641. /**
  29642. An AudioSource that takes the audio from another source, and re-maps its
  29643. input and output channels to a different arrangement.
  29644. You can use this to increase or decrease the number of channels that an
  29645. audio source uses, or to re-order those channels.
  29646. Call the reset() method before using it to set up a default mapping, and then
  29647. the setInputChannelMapping() and setOutputChannelMapping() methods to
  29648. create an appropriate mapping, otherwise no channels will be connected and
  29649. it'll produce silence.
  29650. @see AudioSource
  29651. */
  29652. class ChannelRemappingAudioSource : public AudioSource
  29653. {
  29654. public:
  29655. /** Creates a remapping source that will pass on audio from the given input.
  29656. @param source the input source to use. Make sure that this doesn't
  29657. get deleted before the ChannelRemappingAudioSource object
  29658. @param deleteSourceWhenDeleted if true, the input source will be deleted
  29659. when this object is deleted, if false, the caller is
  29660. responsible for its deletion
  29661. */
  29662. ChannelRemappingAudioSource (AudioSource* source,
  29663. bool deleteSourceWhenDeleted);
  29664. /** Destructor. */
  29665. ~ChannelRemappingAudioSource();
  29666. /** Specifies a number of channels that this audio source must produce from its
  29667. getNextAudioBlock() callback.
  29668. */
  29669. void setNumberOfChannelsToProduce (int requiredNumberOfChannels);
  29670. /** Clears any mapped channels.
  29671. After this, no channels are mapped, so this object will produce silence. Create
  29672. some mappings with setInputChannelMapping() and setOutputChannelMapping().
  29673. */
  29674. void clearAllMappings();
  29675. /** Creates an input channel mapping.
  29676. When the getNextAudioBlock() method is called, the data in channel sourceChannelIndex of the incoming
  29677. data will be sent to destChannelIndex of our input source.
  29678. @param destChannelIndex the index of an input channel in our input audio source (i.e. the
  29679. source specified when this object was created).
  29680. @param sourceChannelIndex the index of the input channel in the incoming audio data buffer
  29681. during our getNextAudioBlock() callback
  29682. */
  29683. void setInputChannelMapping (int destChannelIndex,
  29684. int sourceChannelIndex);
  29685. /** Creates an output channel mapping.
  29686. When the getNextAudioBlock() method is called, the data returned in channel sourceChannelIndex by
  29687. our input audio source will be copied to channel destChannelIndex of the final buffer.
  29688. @param sourceChannelIndex the index of an output channel coming from our input audio source
  29689. (i.e. the source specified when this object was created).
  29690. @param destChannelIndex the index of the output channel in the incoming audio data buffer
  29691. during our getNextAudioBlock() callback
  29692. */
  29693. void setOutputChannelMapping (int sourceChannelIndex,
  29694. int destChannelIndex);
  29695. /** Returns the channel from our input that will be sent to channel inputChannelIndex of
  29696. our input audio source.
  29697. */
  29698. int getRemappedInputChannel (int inputChannelIndex) const;
  29699. /** Returns the output channel to which channel outputChannelIndex of our input audio
  29700. source will be sent to.
  29701. */
  29702. int getRemappedOutputChannel (int outputChannelIndex) const;
  29703. /** Returns an XML object to encapsulate the state of the mappings.
  29704. @see restoreFromXml
  29705. */
  29706. XmlElement* createXml() const;
  29707. /** Restores the mappings from an XML object created by createXML().
  29708. @see createXml
  29709. */
  29710. void restoreFromXml (const XmlElement& e);
  29711. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29712. void releaseResources();
  29713. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29714. private:
  29715. OptionalScopedPointer<AudioSource> source;
  29716. Array <int> remappedInputs, remappedOutputs;
  29717. int requiredNumberOfChannels;
  29718. AudioSampleBuffer buffer;
  29719. AudioSourceChannelInfo remappedInfo;
  29720. CriticalSection lock;
  29721. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChannelRemappingAudioSource);
  29722. };
  29723. #endif // __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  29724. /*** End of inlined file: juce_ChannelRemappingAudioSource.h ***/
  29725. #endif
  29726. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  29727. /*** Start of inlined file: juce_IIRFilterAudioSource.h ***/
  29728. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  29729. #define __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  29730. /*** Start of inlined file: juce_IIRFilter.h ***/
  29731. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  29732. #define __JUCE_IIRFILTER_JUCEHEADER__
  29733. /**
  29734. An IIR filter that can perform low, high, or band-pass filtering on an
  29735. audio signal.
  29736. @see IIRFilterAudioSource
  29737. */
  29738. class JUCE_API IIRFilter
  29739. {
  29740. public:
  29741. /** Creates a filter.
  29742. Initially the filter is inactive, so will have no effect on samples that
  29743. you process with it. Use the appropriate method to turn it into the type
  29744. of filter needed.
  29745. */
  29746. IIRFilter();
  29747. /** Creates a copy of another filter. */
  29748. IIRFilter (const IIRFilter& other);
  29749. /** Destructor. */
  29750. ~IIRFilter();
  29751. /** Resets the filter's processing pipeline, ready to start a new stream of data.
  29752. Note that this clears the processing state, but the type of filter and
  29753. its coefficients aren't changed. To put a filter into an inactive state, use
  29754. the makeInactive() method.
  29755. */
  29756. void reset() noexcept;
  29757. /** Performs the filter operation on the given set of samples.
  29758. */
  29759. void processSamples (float* samples,
  29760. int numSamples) noexcept;
  29761. /** Processes a single sample, without any locking or checking.
  29762. Use this if you need fast processing of a single value, but be aware that
  29763. this isn't thread-safe in the way that processSamples() is.
  29764. */
  29765. float processSingleSampleRaw (float sample) noexcept;
  29766. /** Sets the filter up to act as a low-pass filter.
  29767. */
  29768. void makeLowPass (double sampleRate,
  29769. double frequency) noexcept;
  29770. /** Sets the filter up to act as a high-pass filter.
  29771. */
  29772. void makeHighPass (double sampleRate,
  29773. double frequency) noexcept;
  29774. /** Sets the filter up to act as a low-pass shelf filter with variable Q and gain.
  29775. The gain is a scale factor that the low frequencies are multiplied by, so values
  29776. greater than 1.0 will boost the low frequencies, values less than 1.0 will
  29777. attenuate them.
  29778. */
  29779. void makeLowShelf (double sampleRate,
  29780. double cutOffFrequency,
  29781. double Q,
  29782. float gainFactor) noexcept;
  29783. /** Sets the filter up to act as a high-pass shelf filter with variable Q and gain.
  29784. The gain is a scale factor that the high frequencies are multiplied by, so values
  29785. greater than 1.0 will boost the high frequencies, values less than 1.0 will
  29786. attenuate them.
  29787. */
  29788. void makeHighShelf (double sampleRate,
  29789. double cutOffFrequency,
  29790. double Q,
  29791. float gainFactor) noexcept;
  29792. /** Sets the filter up to act as a band pass filter centred around a
  29793. frequency, with a variable Q and gain.
  29794. The gain is a scale factor that the centre frequencies are multiplied by, so
  29795. values greater than 1.0 will boost the centre frequencies, values less than
  29796. 1.0 will attenuate them.
  29797. */
  29798. void makeBandPass (double sampleRate,
  29799. double centreFrequency,
  29800. double Q,
  29801. float gainFactor) noexcept;
  29802. /** Clears the filter's coefficients so that it becomes inactive.
  29803. */
  29804. void makeInactive() noexcept;
  29805. /** Makes this filter duplicate the set-up of another one.
  29806. */
  29807. void copyCoefficientsFrom (const IIRFilter& other) noexcept;
  29808. protected:
  29809. CriticalSection processLock;
  29810. void setCoefficients (double c1, double c2, double c3,
  29811. double c4, double c5, double c6) noexcept;
  29812. bool active;
  29813. float coefficients[6];
  29814. float x1, x2, y1, y2;
  29815. // (use the copyCoefficientsFrom() method instead of this operator)
  29816. IIRFilter& operator= (const IIRFilter&);
  29817. JUCE_LEAK_DETECTOR (IIRFilter);
  29818. };
  29819. #endif // __JUCE_IIRFILTER_JUCEHEADER__
  29820. /*** End of inlined file: juce_IIRFilter.h ***/
  29821. /**
  29822. An AudioSource that performs an IIR filter on another source.
  29823. */
  29824. class JUCE_API IIRFilterAudioSource : public AudioSource
  29825. {
  29826. public:
  29827. /** Creates a IIRFilterAudioSource for a given input source.
  29828. @param inputSource the input source to read from - this must not be null
  29829. @param deleteInputWhenDeleted if true, the input source will be deleted when
  29830. this object is deleted
  29831. */
  29832. IIRFilterAudioSource (AudioSource* inputSource,
  29833. bool deleteInputWhenDeleted);
  29834. /** Destructor. */
  29835. ~IIRFilterAudioSource();
  29836. /** Changes the filter to use the same parameters as the one being passed in. */
  29837. void setFilterParameters (const IIRFilter& newSettings);
  29838. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29839. void releaseResources();
  29840. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29841. private:
  29842. OptionalScopedPointer<AudioSource> input;
  29843. OwnedArray <IIRFilter> iirFilters;
  29844. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (IIRFilterAudioSource);
  29845. };
  29846. #endif // __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  29847. /*** End of inlined file: juce_IIRFilterAudioSource.h ***/
  29848. #endif
  29849. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  29850. /*** Start of inlined file: juce_MixerAudioSource.h ***/
  29851. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  29852. #define __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  29853. /**
  29854. An AudioSource that mixes together the output of a set of other AudioSources.
  29855. Input sources can be added and removed while the mixer is running as long as their
  29856. prepareToPlay() and releaseResources() methods are called before and after adding
  29857. them to the mixer.
  29858. */
  29859. class JUCE_API MixerAudioSource : public AudioSource
  29860. {
  29861. public:
  29862. /** Creates a MixerAudioSource.
  29863. */
  29864. MixerAudioSource();
  29865. /** Destructor. */
  29866. ~MixerAudioSource();
  29867. /** Adds an input source to the mixer.
  29868. If the mixer is running you'll need to make sure that the input source
  29869. is ready to play by calling its prepareToPlay() method before adding it.
  29870. If the mixer is stopped, then its input sources will be automatically
  29871. prepared when the mixer's prepareToPlay() method is called.
  29872. @param newInput the source to add to the mixer
  29873. @param deleteWhenRemoved if true, then this source will be deleted when
  29874. the mixer is deleted or when removeAllInputs() is
  29875. called (unless the source is previously removed
  29876. with the removeInputSource method)
  29877. */
  29878. void addInputSource (AudioSource* newInput, bool deleteWhenRemoved);
  29879. /** Removes an input source.
  29880. If the mixer is running, this will remove the source but not call its
  29881. releaseResources() method, so the caller might want to do this manually.
  29882. @param input the source to remove
  29883. @param deleteSource whether to delete this source after it's been removed
  29884. */
  29885. void removeInputSource (AudioSource* input, bool deleteSource);
  29886. /** Removes all the input sources.
  29887. If the mixer is running, this will remove the sources but not call their
  29888. releaseResources() method, so the caller might want to do this manually.
  29889. Any sources which were added with the deleteWhenRemoved flag set will be
  29890. deleted by this method.
  29891. */
  29892. void removeAllInputs();
  29893. /** Implementation of the AudioSource method.
  29894. This will call prepareToPlay() on all its input sources.
  29895. */
  29896. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29897. /** Implementation of the AudioSource method.
  29898. This will call releaseResources() on all its input sources.
  29899. */
  29900. void releaseResources();
  29901. /** Implementation of the AudioSource method. */
  29902. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29903. private:
  29904. Array <AudioSource*> inputs;
  29905. BigInteger inputsToDelete;
  29906. CriticalSection lock;
  29907. AudioSampleBuffer tempBuffer;
  29908. double currentSampleRate;
  29909. int bufferSizeExpected;
  29910. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MixerAudioSource);
  29911. };
  29912. #endif // __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  29913. /*** End of inlined file: juce_MixerAudioSource.h ***/
  29914. #endif
  29915. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  29916. #endif
  29917. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  29918. #endif
  29919. #ifndef __JUCE_REVERBAUDIOSOURCE_JUCEHEADER__
  29920. /*** Start of inlined file: juce_ReverbAudioSource.h ***/
  29921. #ifndef __JUCE_REVERBAUDIOSOURCE_JUCEHEADER__
  29922. #define __JUCE_REVERBAUDIOSOURCE_JUCEHEADER__
  29923. /*** Start of inlined file: juce_Reverb.h ***/
  29924. #ifndef __JUCE_REVERB_JUCEHEADER__
  29925. #define __JUCE_REVERB_JUCEHEADER__
  29926. /**
  29927. Performs a simple reverb effect on a stream of audio data.
  29928. This is a simple stereo reverb, based on the technique and tunings used in FreeVerb.
  29929. Use setSampleRate() to prepare it, and then call processStereo() or processMono() to
  29930. apply the reverb to your audio data.
  29931. @see ReverbAudioSource
  29932. */
  29933. class Reverb
  29934. {
  29935. public:
  29936. Reverb()
  29937. {
  29938. setParameters (Parameters());
  29939. setSampleRate (44100.0);
  29940. }
  29941. /** Holds the parameters being used by a Reverb object. */
  29942. struct Parameters
  29943. {
  29944. Parameters() noexcept
  29945. : roomSize (0.5f),
  29946. damping (0.5f),
  29947. wetLevel (0.33f),
  29948. dryLevel (0.4f),
  29949. width (1.0f),
  29950. freezeMode (0)
  29951. {}
  29952. float roomSize; /**< Room size, 0 to 1.0, where 1.0 is big, 0 is small. */
  29953. float damping; /**< Damping, 0 to 1.0, where 0 is not damped, 1.0 is fully damped. */
  29954. float wetLevel; /**< Wet level, 0 to 1.0 */
  29955. float dryLevel; /**< Dry level, 0 to 1.0 */
  29956. float width; /**< Reverb width, 0 to 1.0, where 1.0 is very wide. */
  29957. float freezeMode; /**< Freeze mode - values < 0.5 are "normal" mode, values > 0.5
  29958. put the reverb into a continuous feedback loop. */
  29959. };
  29960. /** Returns the reverb's current parameters. */
  29961. const Parameters& getParameters() const noexcept { return parameters; }
  29962. /** Applies a new set of parameters to the reverb.
  29963. Note that this doesn't attempt to lock the reverb, so if you call this in parallel with
  29964. the process method, you may get artifacts.
  29965. */
  29966. void setParameters (const Parameters& newParams)
  29967. {
  29968. const float wetScaleFactor = 3.0f;
  29969. const float dryScaleFactor = 2.0f;
  29970. const float wet = newParams.wetLevel * wetScaleFactor;
  29971. wet1 = wet * (newParams.width * 0.5f + 0.5f);
  29972. wet2 = wet * (1.0f - newParams.width) * 0.5f;
  29973. dry = newParams.dryLevel * dryScaleFactor;
  29974. gain = isFrozen (newParams.freezeMode) ? 0.0f : 0.015f;
  29975. parameters = newParams;
  29976. shouldUpdateDamping = true;
  29977. }
  29978. /** Sets the sample rate that will be used for the reverb.
  29979. You must call this before the process methods, in order to tell it the correct sample rate.
  29980. */
  29981. void setSampleRate (const double sampleRate)
  29982. {
  29983. jassert (sampleRate > 0);
  29984. static const short combTunings[] = { 1116, 1188, 1277, 1356, 1422, 1491, 1557, 1617 }; // (at 44100Hz)
  29985. static const short allPassTunings[] = { 556, 441, 341, 225 };
  29986. const int stereoSpread = 23;
  29987. const int intSampleRate = (int) sampleRate;
  29988. int i;
  29989. for (i = 0; i < numCombs; ++i)
  29990. {
  29991. comb[0][i].setSize ((intSampleRate * combTunings[i]) / 44100);
  29992. comb[1][i].setSize ((intSampleRate * (combTunings[i] + stereoSpread)) / 44100);
  29993. }
  29994. for (i = 0; i < numAllPasses; ++i)
  29995. {
  29996. allPass[0][i].setSize ((intSampleRate * allPassTunings[i]) / 44100);
  29997. allPass[1][i].setSize ((intSampleRate * (allPassTunings[i] + stereoSpread)) / 44100);
  29998. }
  29999. shouldUpdateDamping = true;
  30000. }
  30001. /** Clears the reverb's buffers. */
  30002. void reset()
  30003. {
  30004. for (int j = 0; j < numChannels; ++j)
  30005. {
  30006. int i;
  30007. for (i = 0; i < numCombs; ++i)
  30008. comb[j][i].clear();
  30009. for (i = 0; i < numAllPasses; ++i)
  30010. allPass[j][i].clear();
  30011. }
  30012. }
  30013. /** Applies the reverb to two stereo channels of audio data. */
  30014. void processStereo (float* const left, float* const right, const int numSamples) noexcept
  30015. {
  30016. jassert (left != nullptr && right != nullptr);
  30017. if (shouldUpdateDamping)
  30018. updateDamping();
  30019. for (int i = 0; i < numSamples; ++i)
  30020. {
  30021. const float input = (left[i] + right[i]) * gain;
  30022. float outL = 0, outR = 0;
  30023. int j;
  30024. for (j = 0; j < numCombs; ++j) // accumulate the comb filters in parallel
  30025. {
  30026. outL += comb[0][j].process (input);
  30027. outR += comb[1][j].process (input);
  30028. }
  30029. for (j = 0; j < numAllPasses; ++j) // run the allpass filters in series
  30030. {
  30031. outL = allPass[0][j].process (outL);
  30032. outR = allPass[1][j].process (outR);
  30033. }
  30034. left[i] = outL * wet1 + outR * wet2 + left[i] * dry;
  30035. right[i] = outR * wet1 + outL * wet2 + right[i] * dry;
  30036. }
  30037. }
  30038. /** Applies the reverb to a single mono channel of audio data. */
  30039. void processMono (float* const samples, const int numSamples) noexcept
  30040. {
  30041. jassert (samples != nullptr);
  30042. if (shouldUpdateDamping)
  30043. updateDamping();
  30044. for (int i = 0; i < numSamples; ++i)
  30045. {
  30046. const float input = samples[i] * gain;
  30047. float output = 0;
  30048. int j;
  30049. for (j = 0; j < numCombs; ++j) // accumulate the comb filters in parallel
  30050. output += comb[0][j].process (input);
  30051. for (j = 0; j < numAllPasses; ++j) // run the allpass filters in series
  30052. output = allPass[0][j].process (output);
  30053. samples[i] = output * wet1 + input * dry;
  30054. }
  30055. }
  30056. private:
  30057. Parameters parameters;
  30058. volatile bool shouldUpdateDamping;
  30059. float gain, wet1, wet2, dry;
  30060. inline static bool isFrozen (const float freezeMode) noexcept { return freezeMode >= 0.5f; }
  30061. void updateDamping() noexcept
  30062. {
  30063. const float roomScaleFactor = 0.28f;
  30064. const float roomOffset = 0.7f;
  30065. const float dampScaleFactor = 0.4f;
  30066. shouldUpdateDamping = false;
  30067. if (isFrozen (parameters.freezeMode))
  30068. setDamping (1.0f, 0.0f);
  30069. else
  30070. setDamping (parameters.damping * dampScaleFactor,
  30071. parameters.roomSize * roomScaleFactor + roomOffset);
  30072. }
  30073. void setDamping (const float dampingToUse, const float roomSizeToUse) noexcept
  30074. {
  30075. for (int j = 0; j < numChannels; ++j)
  30076. for (int i = numCombs; --i >= 0;)
  30077. comb[j][i].setFeedbackAndDamp (roomSizeToUse, dampingToUse);
  30078. }
  30079. class CombFilter
  30080. {
  30081. public:
  30082. CombFilter() noexcept : bufferSize (0), bufferIndex (0) {}
  30083. void setSize (const int size)
  30084. {
  30085. if (size != bufferSize)
  30086. {
  30087. bufferIndex = 0;
  30088. buffer.malloc (size);
  30089. bufferSize = size;
  30090. }
  30091. clear();
  30092. }
  30093. void clear() noexcept
  30094. {
  30095. last = 0;
  30096. buffer.clear (bufferSize);
  30097. }
  30098. void setFeedbackAndDamp (const float f, const float d) noexcept
  30099. {
  30100. damp1 = d;
  30101. damp2 = 1.0f - d;
  30102. feedback = f;
  30103. }
  30104. inline float process (const float input) noexcept
  30105. {
  30106. const float output = buffer [bufferIndex];
  30107. last = (output * damp2) + (last * damp1);
  30108. JUCE_UNDENORMALISE (last);
  30109. float temp = input + (last * feedback);
  30110. JUCE_UNDENORMALISE (temp);
  30111. buffer [bufferIndex] = temp;
  30112. bufferIndex = (bufferIndex + 1) % bufferSize;
  30113. return output;
  30114. }
  30115. private:
  30116. HeapBlock<float> buffer;
  30117. int bufferSize, bufferIndex;
  30118. float feedback, last, damp1, damp2;
  30119. JUCE_DECLARE_NON_COPYABLE (CombFilter);
  30120. };
  30121. class AllPassFilter
  30122. {
  30123. public:
  30124. AllPassFilter() noexcept : bufferSize (0), bufferIndex (0) {}
  30125. void setSize (const int size)
  30126. {
  30127. if (size != bufferSize)
  30128. {
  30129. bufferIndex = 0;
  30130. buffer.malloc (size);
  30131. bufferSize = size;
  30132. }
  30133. clear();
  30134. }
  30135. void clear() noexcept
  30136. {
  30137. buffer.clear (bufferSize);
  30138. }
  30139. inline float process (const float input) noexcept
  30140. {
  30141. const float bufferedValue = buffer [bufferIndex];
  30142. float temp = input + (bufferedValue * 0.5f);
  30143. JUCE_UNDENORMALISE (temp);
  30144. buffer [bufferIndex] = temp;
  30145. bufferIndex = (bufferIndex + 1) % bufferSize;
  30146. return bufferedValue - input;
  30147. }
  30148. private:
  30149. HeapBlock<float> buffer;
  30150. int bufferSize, bufferIndex;
  30151. JUCE_DECLARE_NON_COPYABLE (AllPassFilter);
  30152. };
  30153. enum { numCombs = 8, numAllPasses = 4, numChannels = 2 };
  30154. CombFilter comb [numChannels][numCombs];
  30155. AllPassFilter allPass [numChannels][numAllPasses];
  30156. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Reverb);
  30157. };
  30158. #endif // __JUCE_REVERB_JUCEHEADER__
  30159. /*** End of inlined file: juce_Reverb.h ***/
  30160. /**
  30161. An AudioSource that uses the Reverb class to apply a reverb to another AudioSource.
  30162. @see Reverb
  30163. */
  30164. class JUCE_API ReverbAudioSource : public AudioSource
  30165. {
  30166. public:
  30167. /** Creates a ReverbAudioSource to process a given input source.
  30168. @param inputSource the input source to read from - this must not be null
  30169. @param deleteInputWhenDeleted if true, the input source will be deleted when
  30170. this object is deleted
  30171. */
  30172. ReverbAudioSource (AudioSource* inputSource,
  30173. bool deleteInputWhenDeleted);
  30174. /** Destructor. */
  30175. ~ReverbAudioSource();
  30176. /** Returns the parameters from the reverb. */
  30177. const Reverb::Parameters& getParameters() const noexcept { return reverb.getParameters(); }
  30178. /** Changes the reverb's parameters. */
  30179. void setParameters (const Reverb::Parameters& newParams);
  30180. void setBypassed (bool isBypassed) noexcept;
  30181. bool isBypassed() const noexcept { return bypass; }
  30182. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  30183. void releaseResources();
  30184. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  30185. private:
  30186. CriticalSection lock;
  30187. OptionalScopedPointer<AudioSource> input;
  30188. Reverb reverb;
  30189. volatile bool bypass;
  30190. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ReverbAudioSource);
  30191. };
  30192. #endif // __JUCE_REVERBAUDIOSOURCE_JUCEHEADER__
  30193. /*** End of inlined file: juce_ReverbAudioSource.h ***/
  30194. #endif
  30195. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  30196. /*** Start of inlined file: juce_ToneGeneratorAudioSource.h ***/
  30197. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  30198. #define __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  30199. /**
  30200. A simple AudioSource that generates a sine wave.
  30201. */
  30202. class JUCE_API ToneGeneratorAudioSource : public AudioSource
  30203. {
  30204. public:
  30205. /** Creates a ToneGeneratorAudioSource. */
  30206. ToneGeneratorAudioSource();
  30207. /** Destructor. */
  30208. ~ToneGeneratorAudioSource();
  30209. /** Sets the signal's amplitude. */
  30210. void setAmplitude (float newAmplitude);
  30211. /** Sets the signal's frequency. */
  30212. void setFrequency (double newFrequencyHz);
  30213. /** Implementation of the AudioSource method. */
  30214. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  30215. /** Implementation of the AudioSource method. */
  30216. void releaseResources();
  30217. /** Implementation of the AudioSource method. */
  30218. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  30219. private:
  30220. double frequency, sampleRate;
  30221. double currentPhase, phasePerSample;
  30222. float amplitude;
  30223. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToneGeneratorAudioSource);
  30224. };
  30225. #endif // __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  30226. /*** End of inlined file: juce_ToneGeneratorAudioSource.h ***/
  30227. #endif
  30228. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  30229. /*** Start of inlined file: juce_AudioDeviceManager.h ***/
  30230. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  30231. #define __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  30232. /*** Start of inlined file: juce_AudioIODeviceType.h ***/
  30233. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  30234. #define __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  30235. class AudioDeviceManager;
  30236. /**
  30237. Represents a type of audio driver, such as DirectSound, ASIO, CoreAudio, etc.
  30238. To get a list of available audio driver types, use the AudioDeviceManager::createAudioDeviceTypes()
  30239. method. Each of the objects returned can then be used to list the available
  30240. devices of that type. E.g.
  30241. @code
  30242. OwnedArray <AudioIODeviceType> types;
  30243. myAudioDeviceManager.createAudioDeviceTypes (types);
  30244. for (int i = 0; i < types.size(); ++i)
  30245. {
  30246. String typeName (types[i]->getTypeName()); // This will be things like "DirectSound", "CoreAudio", etc.
  30247. types[i]->scanForDevices(); // This must be called before getting the list of devices
  30248. StringArray deviceNames (types[i]->getDeviceNames()); // This will now return a list of available devices of this type
  30249. for (int j = 0; j < deviceNames.size(); ++j)
  30250. {
  30251. AudioIODevice* device = types[i]->createDevice (deviceNames [j]);
  30252. ...
  30253. }
  30254. }
  30255. @endcode
  30256. For an easier way of managing audio devices and their settings, have a look at the
  30257. AudioDeviceManager class.
  30258. @see AudioIODevice, AudioDeviceManager
  30259. */
  30260. class JUCE_API AudioIODeviceType
  30261. {
  30262. public:
  30263. /** Returns the name of this type of driver that this object manages.
  30264. This will be something like "DirectSound", "ASIO", "CoreAudio", "ALSA", etc.
  30265. */
  30266. const String& getTypeName() const noexcept { return typeName; }
  30267. /** Refreshes the object's cached list of known devices.
  30268. This must be called at least once before calling getDeviceNames() or any of
  30269. the other device creation methods.
  30270. */
  30271. virtual void scanForDevices() = 0;
  30272. /** Returns the list of available devices of this type.
  30273. The scanForDevices() method must have been called to create this list.
  30274. @param wantInputNames only really used by DirectSound where devices are split up
  30275. into inputs and outputs, this indicates whether to use
  30276. the input or output name to refer to a pair of devices.
  30277. */
  30278. virtual StringArray getDeviceNames (bool wantInputNames = false) const = 0;
  30279. /** Returns the name of the default device.
  30280. This will be one of the names from the getDeviceNames() list.
  30281. @param forInput if true, this means that a default input device should be
  30282. returned; if false, it should return the default output
  30283. */
  30284. virtual int getDefaultDeviceIndex (bool forInput) const = 0;
  30285. /** Returns the index of a given device in the list of device names.
  30286. If asInput is true, it shows the index in the inputs list, otherwise it
  30287. looks for it in the outputs list.
  30288. */
  30289. virtual int getIndexOfDevice (AudioIODevice* device, bool asInput) const = 0;
  30290. /** Returns true if two different devices can be used for the input and output.
  30291. */
  30292. virtual bool hasSeparateInputsAndOutputs() const = 0;
  30293. /** Creates one of the devices of this type.
  30294. The deviceName must be one of the strings returned by getDeviceNames(), and
  30295. scanForDevices() must have been called before this method is used.
  30296. */
  30297. virtual AudioIODevice* createDevice (const String& outputDeviceName,
  30298. const String& inputDeviceName) = 0;
  30299. /**
  30300. A class for receiving events when audio devices are inserted or removed.
  30301. You can register a AudioIODeviceType::Listener with an~AudioIODeviceType object
  30302. using the AudioIODeviceType::addListener() method, and it will be called when
  30303. devices of that type are added or removed.
  30304. @see AudioIODeviceType::addListener, AudioIODeviceType::removeListener
  30305. */
  30306. class Listener
  30307. {
  30308. public:
  30309. virtual ~Listener() {}
  30310. /** Called when the list of available audio devices changes. */
  30311. virtual void audioDeviceListChanged() = 0;
  30312. };
  30313. /** Adds a listener that will be called when this type of device is added or
  30314. removed from the system.
  30315. */
  30316. void addListener (Listener* listener);
  30317. /** Removes a listener that was previously added with addListener(). */
  30318. void removeListener (Listener* listener);
  30319. /** Destructor. */
  30320. virtual ~AudioIODeviceType();
  30321. /** Creates a CoreAudio device type if it's available on this platform, or returns null. */
  30322. static AudioIODeviceType* createAudioIODeviceType_CoreAudio();
  30323. /** Creates an iOS device type if it's available on this platform, or returns null. */
  30324. static AudioIODeviceType* createAudioIODeviceType_iOSAudio();
  30325. /** Creates a WASAPI device type if it's available on this platform, or returns null. */
  30326. static AudioIODeviceType* createAudioIODeviceType_WASAPI();
  30327. /** Creates a DirectSound device type if it's available on this platform, or returns null. */
  30328. static AudioIODeviceType* createAudioIODeviceType_DirectSound();
  30329. /** Creates an ASIO device type if it's available on this platform, or returns null. */
  30330. static AudioIODeviceType* createAudioIODeviceType_ASIO();
  30331. /** Creates an ALSA device type if it's available on this platform, or returns null. */
  30332. static AudioIODeviceType* createAudioIODeviceType_ALSA();
  30333. /** Creates a JACK device type if it's available on this platform, or returns null. */
  30334. static AudioIODeviceType* createAudioIODeviceType_JACK();
  30335. /** Creates an Android device type if it's available on this platform, or returns null. */
  30336. static AudioIODeviceType* createAudioIODeviceType_Android();
  30337. protected:
  30338. explicit AudioIODeviceType (const String& typeName);
  30339. /** Synchronously calls all the registered device list change listeners. */
  30340. void callDeviceChangeListeners();
  30341. private:
  30342. String typeName;
  30343. ListenerList<Listener> listeners;
  30344. JUCE_DECLARE_NON_COPYABLE (AudioIODeviceType);
  30345. };
  30346. #endif // __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  30347. /*** End of inlined file: juce_AudioIODeviceType.h ***/
  30348. /*** Start of inlined file: juce_MidiInput.h ***/
  30349. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  30350. #define __JUCE_MIDIINPUT_JUCEHEADER__
  30351. /*** Start of inlined file: juce_MidiMessage.h ***/
  30352. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  30353. #define __JUCE_MIDIMESSAGE_JUCEHEADER__
  30354. /**
  30355. Encapsulates a MIDI message.
  30356. @see MidiMessageSequence, MidiOutput, MidiInput
  30357. */
  30358. class JUCE_API MidiMessage
  30359. {
  30360. public:
  30361. /** Creates a 3-byte short midi message.
  30362. @param byte1 message byte 1
  30363. @param byte2 message byte 2
  30364. @param byte3 message byte 3
  30365. @param timeStamp the time to give the midi message - this value doesn't
  30366. use any particular units, so will be application-specific
  30367. */
  30368. MidiMessage (int byte1, int byte2, int byte3, double timeStamp = 0) noexcept;
  30369. /** Creates a 2-byte short midi message.
  30370. @param byte1 message byte 1
  30371. @param byte2 message byte 2
  30372. @param timeStamp the time to give the midi message - this value doesn't
  30373. use any particular units, so will be application-specific
  30374. */
  30375. MidiMessage (int byte1, int byte2, double timeStamp = 0) noexcept;
  30376. /** Creates a 1-byte short midi message.
  30377. @param byte1 message byte 1
  30378. @param timeStamp the time to give the midi message - this value doesn't
  30379. use any particular units, so will be application-specific
  30380. */
  30381. MidiMessage (int byte1, double timeStamp = 0) noexcept;
  30382. /** Creates a midi message from a block of data. */
  30383. MidiMessage (const void* data, int numBytes, double timeStamp = 0);
  30384. /** Reads the next midi message from some data.
  30385. This will read as many bytes from a data stream as it needs to make a
  30386. complete message, and will return the number of bytes it used. This lets
  30387. you read a sequence of midi messages from a file or stream.
  30388. @param data the data to read from
  30389. @param maxBytesToUse the maximum number of bytes it's allowed to read
  30390. @param numBytesUsed returns the number of bytes that were actually needed
  30391. @param lastStatusByte in a sequence of midi messages, the initial byte
  30392. can be dropped from a message if it's the same as the
  30393. first byte of the previous message, so this lets you
  30394. supply the byte to use if the first byte of the message
  30395. has in fact been dropped.
  30396. @param timeStamp the time to give the midi message - this value doesn't
  30397. use any particular units, so will be application-specific
  30398. */
  30399. MidiMessage (const void* data, int maxBytesToUse,
  30400. int& numBytesUsed, uint8 lastStatusByte,
  30401. double timeStamp = 0);
  30402. /** Creates an active-sense message.
  30403. Since the MidiMessage has to contain a valid message, this default constructor
  30404. just initialises it with an empty sysex message.
  30405. */
  30406. MidiMessage() noexcept;
  30407. /** Creates a copy of another midi message. */
  30408. MidiMessage (const MidiMessage& other);
  30409. /** Creates a copy of another midi message, with a different timestamp. */
  30410. MidiMessage (const MidiMessage& other, double newTimeStamp);
  30411. /** Destructor. */
  30412. ~MidiMessage();
  30413. /** Copies this message from another one. */
  30414. MidiMessage& operator= (const MidiMessage& other);
  30415. /** Returns a pointer to the raw midi data.
  30416. @see getRawDataSize
  30417. */
  30418. uint8* getRawData() const noexcept { return data; }
  30419. /** Returns the number of bytes of data in the message.
  30420. @see getRawData
  30421. */
  30422. int getRawDataSize() const noexcept { return size; }
  30423. /** Returns the timestamp associated with this message.
  30424. The exact meaning of this time and its units will vary, as messages are used in
  30425. a variety of different contexts.
  30426. If you're getting the message from a midi file, this could be a time in seconds, or
  30427. a number of ticks - see MidiFile::convertTimestampTicksToSeconds().
  30428. If the message is being used in a MidiBuffer, it might indicate the number of
  30429. audio samples from the start of the buffer.
  30430. If the message was created by a MidiInput, see MidiInputCallback::handleIncomingMidiMessage()
  30431. for details of the way that it initialises this value.
  30432. @see setTimeStamp, addToTimeStamp
  30433. */
  30434. double getTimeStamp() const noexcept { return timeStamp; }
  30435. /** Changes the message's associated timestamp.
  30436. The units for the timestamp will be application-specific - see the notes for getTimeStamp().
  30437. @see addToTimeStamp, getTimeStamp
  30438. */
  30439. void setTimeStamp (double newTimestamp) noexcept { timeStamp = newTimestamp; }
  30440. /** Adds a value to the message's timestamp.
  30441. The units for the timestamp will be application-specific.
  30442. */
  30443. void addToTimeStamp (double delta) noexcept { timeStamp += delta; }
  30444. /** Returns the midi channel associated with the message.
  30445. @returns a value 1 to 16 if the message has a channel, or 0 if it hasn't (e.g.
  30446. if it's a sysex)
  30447. @see isForChannel, setChannel
  30448. */
  30449. int getChannel() const noexcept;
  30450. /** Returns true if the message applies to the given midi channel.
  30451. @param channelNumber the channel number to look for, in the range 1 to 16
  30452. @see getChannel, setChannel
  30453. */
  30454. bool isForChannel (int channelNumber) const noexcept;
  30455. /** Changes the message's midi channel.
  30456. This won't do anything for non-channel messages like sysexes.
  30457. @param newChannelNumber the channel number to change it to, in the range 1 to 16
  30458. */
  30459. void setChannel (int newChannelNumber) noexcept;
  30460. /** Returns true if this is a system-exclusive message.
  30461. */
  30462. bool isSysEx() const noexcept;
  30463. /** Returns a pointer to the sysex data inside the message.
  30464. If this event isn't a sysex event, it'll return 0.
  30465. @see getSysExDataSize
  30466. */
  30467. const uint8* getSysExData() const noexcept;
  30468. /** Returns the size of the sysex data.
  30469. This value excludes the 0xf0 header byte and the 0xf7 at the end.
  30470. @see getSysExData
  30471. */
  30472. int getSysExDataSize() const noexcept;
  30473. /** Returns true if this message is a 'key-down' event.
  30474. @param returnTrueForVelocity0 if true, then if this event is a note-on with
  30475. velocity 0, it will still be considered to be a note-on and the
  30476. method will return true. If returnTrueForVelocity0 is false, then
  30477. if this is a note-on event with velocity 0, it'll be regarded as
  30478. a note-off, and the method will return false
  30479. @see isNoteOff, getNoteNumber, getVelocity, noteOn
  30480. */
  30481. bool isNoteOn (bool returnTrueForVelocity0 = false) const noexcept;
  30482. /** Creates a key-down message (using a floating-point velocity).
  30483. @param channel the midi channel, in the range 1 to 16
  30484. @param noteNumber the key number, 0 to 127
  30485. @param velocity in the range 0 to 1.0
  30486. @see isNoteOn
  30487. */
  30488. static MidiMessage noteOn (int channel, int noteNumber, float velocity) noexcept;
  30489. /** Creates a key-down message (using an integer velocity).
  30490. @param channel the midi channel, in the range 1 to 16
  30491. @param noteNumber the key number, 0 to 127
  30492. @param velocity in the range 0 to 127
  30493. @see isNoteOn
  30494. */
  30495. static MidiMessage noteOn (int channel, int noteNumber, uint8 velocity) noexcept;
  30496. /** Returns true if this message is a 'key-up' event.
  30497. If returnTrueForNoteOnVelocity0 is true, then his will also return true
  30498. for a note-on event with a velocity of 0.
  30499. @see isNoteOn, getNoteNumber, getVelocity, noteOff
  30500. */
  30501. bool isNoteOff (bool returnTrueForNoteOnVelocity0 = true) const noexcept;
  30502. /** Creates a key-up message.
  30503. @param channel the midi channel, in the range 1 to 16
  30504. @param noteNumber the key number, 0 to 127
  30505. @param velocity in the range 0 to 127
  30506. @see isNoteOff
  30507. */
  30508. static MidiMessage noteOff (int channel, int noteNumber, uint8 velocity = 0) noexcept;
  30509. /** Returns true if this message is a 'key-down' or 'key-up' event.
  30510. @see isNoteOn, isNoteOff
  30511. */
  30512. bool isNoteOnOrOff() const noexcept;
  30513. /** Returns the midi note number for note-on and note-off messages.
  30514. If the message isn't a note-on or off, the value returned is undefined.
  30515. @see isNoteOff, getMidiNoteName, getMidiNoteInHertz, setNoteNumber
  30516. */
  30517. int getNoteNumber() const noexcept;
  30518. /** Changes the midi note number of a note-on or note-off message.
  30519. If the message isn't a note on or off, this will do nothing.
  30520. */
  30521. void setNoteNumber (int newNoteNumber) noexcept;
  30522. /** Returns the velocity of a note-on or note-off message.
  30523. The value returned will be in the range 0 to 127.
  30524. If the message isn't a note-on or off event, it will return 0.
  30525. @see getFloatVelocity
  30526. */
  30527. uint8 getVelocity() const noexcept;
  30528. /** Returns the velocity of a note-on or note-off message.
  30529. The value returned will be in the range 0 to 1.0
  30530. If the message isn't a note-on or off event, it will return 0.
  30531. @see getVelocity, setVelocity
  30532. */
  30533. float getFloatVelocity() const noexcept;
  30534. /** Changes the velocity of a note-on or note-off message.
  30535. If the message isn't a note on or off, this will do nothing.
  30536. @param newVelocity the new velocity, in the range 0 to 1.0
  30537. @see getFloatVelocity, multiplyVelocity
  30538. */
  30539. void setVelocity (float newVelocity) noexcept;
  30540. /** Multiplies the velocity of a note-on or note-off message by a given amount.
  30541. If the message isn't a note on or off, this will do nothing.
  30542. @param scaleFactor the value by which to multiply the velocity
  30543. @see setVelocity
  30544. */
  30545. void multiplyVelocity (float scaleFactor) noexcept;
  30546. /** Returns true if this message is a 'sustain pedal down' controller message. */
  30547. bool isSustainPedalOn() const noexcept;
  30548. /** Returns true if this message is a 'sustain pedal up' controller message. */
  30549. bool isSustainPedalOff() const noexcept;
  30550. /** Returns true if this message is a 'sostenuto pedal down' controller message. */
  30551. bool isSostenutoPedalOn() const noexcept;
  30552. /** Returns true if this message is a 'sostenuto pedal up' controller message. */
  30553. bool isSostenutoPedalOff() const noexcept;
  30554. /** Returns true if this message is a 'soft pedal down' controller message. */
  30555. bool isSoftPedalOn() const noexcept;
  30556. /** Returns true if this message is a 'soft pedal up' controller message. */
  30557. bool isSoftPedalOff() const noexcept;
  30558. /** Returns true if the message is a program (patch) change message.
  30559. @see getProgramChangeNumber, getGMInstrumentName
  30560. */
  30561. bool isProgramChange() const noexcept;
  30562. /** Returns the new program number of a program change message.
  30563. If the message isn't a program change, the value returned will be
  30564. nonsense.
  30565. @see isProgramChange, getGMInstrumentName
  30566. */
  30567. int getProgramChangeNumber() const noexcept;
  30568. /** Creates a program-change message.
  30569. @param channel the midi channel, in the range 1 to 16
  30570. @param programNumber the midi program number, 0 to 127
  30571. @see isProgramChange, getGMInstrumentName
  30572. */
  30573. static MidiMessage programChange (int channel, int programNumber) noexcept;
  30574. /** Returns true if the message is a pitch-wheel move.
  30575. @see getPitchWheelValue, pitchWheel
  30576. */
  30577. bool isPitchWheel() const noexcept;
  30578. /** Returns the pitch wheel position from a pitch-wheel move message.
  30579. The value returned is a 14-bit number from 0 to 0x3fff, indicating the wheel position.
  30580. If called for messages which aren't pitch wheel events, the number returned will be
  30581. nonsense.
  30582. @see isPitchWheel
  30583. */
  30584. int getPitchWheelValue() const noexcept;
  30585. /** Creates a pitch-wheel move message.
  30586. @param channel the midi channel, in the range 1 to 16
  30587. @param position the wheel position, in the range 0 to 16383
  30588. @see isPitchWheel
  30589. */
  30590. static MidiMessage pitchWheel (int channel, int position) noexcept;
  30591. /** Returns true if the message is an aftertouch event.
  30592. For aftertouch events, use the getNoteNumber() method to find out the key
  30593. that it applies to, and getAftertouchValue() to find out the amount. Use
  30594. getChannel() to find out the channel.
  30595. @see getAftertouchValue, getNoteNumber
  30596. */
  30597. bool isAftertouch() const noexcept;
  30598. /** Returns the amount of aftertouch from an aftertouch messages.
  30599. The value returned is in the range 0 to 127, and will be nonsense for messages
  30600. other than aftertouch messages.
  30601. @see isAftertouch
  30602. */
  30603. int getAfterTouchValue() const noexcept;
  30604. /** Creates an aftertouch message.
  30605. @param channel the midi channel, in the range 1 to 16
  30606. @param noteNumber the key number, 0 to 127
  30607. @param aftertouchAmount the amount of aftertouch, 0 to 127
  30608. @see isAftertouch
  30609. */
  30610. static MidiMessage aftertouchChange (int channel,
  30611. int noteNumber,
  30612. int aftertouchAmount) noexcept;
  30613. /** Returns true if the message is a channel-pressure change event.
  30614. This is like aftertouch, but common to the whole channel rather than a specific
  30615. note. Use getChannelPressureValue() to find out the pressure, and getChannel()
  30616. to find out the channel.
  30617. @see channelPressureChange
  30618. */
  30619. bool isChannelPressure() const noexcept;
  30620. /** Returns the pressure from a channel pressure change message.
  30621. @returns the pressure, in the range 0 to 127
  30622. @see isChannelPressure, channelPressureChange
  30623. */
  30624. int getChannelPressureValue() const noexcept;
  30625. /** Creates a channel-pressure change event.
  30626. @param channel the midi channel: 1 to 16
  30627. @param pressure the pressure, 0 to 127
  30628. @see isChannelPressure
  30629. */
  30630. static MidiMessage channelPressureChange (int channel, int pressure) noexcept;
  30631. /** Returns true if this is a midi controller message.
  30632. @see getControllerNumber, getControllerValue, controllerEvent
  30633. */
  30634. bool isController() const noexcept;
  30635. /** Returns the controller number of a controller message.
  30636. The name of the controller can be looked up using the getControllerName() method.
  30637. Note that the value returned is invalid for messages that aren't controller changes.
  30638. @see isController, getControllerName, getControllerValue
  30639. */
  30640. int getControllerNumber() const noexcept;
  30641. /** Returns the controller value from a controller message.
  30642. A value 0 to 127 is returned to indicate the new controller position.
  30643. Note that the value returned is invalid for messages that aren't controller changes.
  30644. @see isController, getControllerNumber
  30645. */
  30646. int getControllerValue() const noexcept;
  30647. /** Returns true if this message is a controller message and if it has the specified
  30648. controller type.
  30649. */
  30650. bool isControllerOfType (int controllerType) const noexcept;
  30651. /** Creates a controller message.
  30652. @param channel the midi channel, in the range 1 to 16
  30653. @param controllerType the type of controller
  30654. @param value the controller value
  30655. @see isController
  30656. */
  30657. static MidiMessage controllerEvent (int channel,
  30658. int controllerType,
  30659. int value) noexcept;
  30660. /** Checks whether this message is an all-notes-off message.
  30661. @see allNotesOff
  30662. */
  30663. bool isAllNotesOff() const noexcept;
  30664. /** Checks whether this message is an all-sound-off message.
  30665. @see allSoundOff
  30666. */
  30667. bool isAllSoundOff() const noexcept;
  30668. /** Creates an all-notes-off message.
  30669. @param channel the midi channel, in the range 1 to 16
  30670. @see isAllNotesOff
  30671. */
  30672. static MidiMessage allNotesOff (int channel) noexcept;
  30673. /** Creates an all-sound-off message.
  30674. @param channel the midi channel, in the range 1 to 16
  30675. @see isAllSoundOff
  30676. */
  30677. static MidiMessage allSoundOff (int channel) noexcept;
  30678. /** Creates an all-controllers-off message.
  30679. @param channel the midi channel, in the range 1 to 16
  30680. */
  30681. static MidiMessage allControllersOff (int channel) noexcept;
  30682. /** Returns true if this event is a meta-event.
  30683. Meta-events are things like tempo changes, track names, etc.
  30684. @see getMetaEventType, isTrackMetaEvent, isEndOfTrackMetaEvent,
  30685. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  30686. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  30687. */
  30688. bool isMetaEvent() const noexcept;
  30689. /** Returns a meta-event's type number.
  30690. If the message isn't a meta-event, this will return -1.
  30691. @see isMetaEvent, isTrackMetaEvent, isEndOfTrackMetaEvent,
  30692. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  30693. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  30694. */
  30695. int getMetaEventType() const noexcept;
  30696. /** Returns a pointer to the data in a meta-event.
  30697. @see isMetaEvent, getMetaEventLength
  30698. */
  30699. const uint8* getMetaEventData() const noexcept;
  30700. /** Returns the length of the data for a meta-event.
  30701. @see isMetaEvent, getMetaEventData
  30702. */
  30703. int getMetaEventLength() const noexcept;
  30704. /** Returns true if this is a 'track' meta-event. */
  30705. bool isTrackMetaEvent() const noexcept;
  30706. /** Returns true if this is an 'end-of-track' meta-event. */
  30707. bool isEndOfTrackMetaEvent() const noexcept;
  30708. /** Creates an end-of-track meta-event.
  30709. @see isEndOfTrackMetaEvent
  30710. */
  30711. static MidiMessage endOfTrack() noexcept;
  30712. /** Returns true if this is an 'track name' meta-event.
  30713. You can use the getTextFromTextMetaEvent() method to get the track's name.
  30714. */
  30715. bool isTrackNameEvent() const noexcept;
  30716. /** Returns true if this is a 'text' meta-event.
  30717. @see getTextFromTextMetaEvent
  30718. */
  30719. bool isTextMetaEvent() const noexcept;
  30720. /** Returns the text from a text meta-event.
  30721. @see isTextMetaEvent
  30722. */
  30723. String getTextFromTextMetaEvent() const;
  30724. /** Returns true if this is a 'tempo' meta-event.
  30725. @see getTempoMetaEventTickLength, getTempoSecondsPerQuarterNote
  30726. */
  30727. bool isTempoMetaEvent() const noexcept;
  30728. /** Returns the tick length from a tempo meta-event.
  30729. @param timeFormat the 16-bit time format value from the midi file's header.
  30730. @returns the tick length (in seconds).
  30731. @see isTempoMetaEvent
  30732. */
  30733. double getTempoMetaEventTickLength (short timeFormat) const noexcept;
  30734. /** Calculates the seconds-per-quarter-note from a tempo meta-event.
  30735. @see isTempoMetaEvent, getTempoMetaEventTickLength
  30736. */
  30737. double getTempoSecondsPerQuarterNote() const noexcept;
  30738. /** Creates a tempo meta-event.
  30739. @see isTempoMetaEvent
  30740. */
  30741. static MidiMessage tempoMetaEvent (int microsecondsPerQuarterNote) noexcept;
  30742. /** Returns true if this is a 'time-signature' meta-event.
  30743. @see getTimeSignatureInfo
  30744. */
  30745. bool isTimeSignatureMetaEvent() const noexcept;
  30746. /** Returns the time-signature values from a time-signature meta-event.
  30747. @see isTimeSignatureMetaEvent
  30748. */
  30749. void getTimeSignatureInfo (int& numerator, int& denominator) const noexcept;
  30750. /** Creates a time-signature meta-event.
  30751. @see isTimeSignatureMetaEvent
  30752. */
  30753. static MidiMessage timeSignatureMetaEvent (int numerator, int denominator);
  30754. /** Returns true if this is a 'key-signature' meta-event.
  30755. @see getKeySignatureNumberOfSharpsOrFlats
  30756. */
  30757. bool isKeySignatureMetaEvent() const noexcept;
  30758. /** Returns the key from a key-signature meta-event.
  30759. @see isKeySignatureMetaEvent
  30760. */
  30761. int getKeySignatureNumberOfSharpsOrFlats() const noexcept;
  30762. /** Returns true if this is a 'channel' meta-event.
  30763. A channel meta-event specifies the midi channel that should be used
  30764. for subsequent meta-events.
  30765. @see getMidiChannelMetaEventChannel
  30766. */
  30767. bool isMidiChannelMetaEvent() const noexcept;
  30768. /** Returns the channel number from a channel meta-event.
  30769. @returns the channel, in the range 1 to 16.
  30770. @see isMidiChannelMetaEvent
  30771. */
  30772. int getMidiChannelMetaEventChannel() const noexcept;
  30773. /** Creates a midi channel meta-event.
  30774. @param channel the midi channel, in the range 1 to 16
  30775. @see isMidiChannelMetaEvent
  30776. */
  30777. static MidiMessage midiChannelMetaEvent (int channel) noexcept;
  30778. /** Returns true if this is an active-sense message. */
  30779. bool isActiveSense() const noexcept;
  30780. /** Returns true if this is a midi start event.
  30781. @see midiStart
  30782. */
  30783. bool isMidiStart() const noexcept;
  30784. /** Creates a midi start event. */
  30785. static MidiMessage midiStart() noexcept;
  30786. /** Returns true if this is a midi continue event.
  30787. @see midiContinue
  30788. */
  30789. bool isMidiContinue() const noexcept;
  30790. /** Creates a midi continue event. */
  30791. static MidiMessage midiContinue() noexcept;
  30792. /** Returns true if this is a midi stop event.
  30793. @see midiStop
  30794. */
  30795. bool isMidiStop() const noexcept;
  30796. /** Creates a midi stop event. */
  30797. static MidiMessage midiStop() noexcept;
  30798. /** Returns true if this is a midi clock event.
  30799. @see midiClock, songPositionPointer
  30800. */
  30801. bool isMidiClock() const noexcept;
  30802. /** Creates a midi clock event. */
  30803. static MidiMessage midiClock() noexcept;
  30804. /** Returns true if this is a song-position-pointer message.
  30805. @see getSongPositionPointerMidiBeat, songPositionPointer
  30806. */
  30807. bool isSongPositionPointer() const noexcept;
  30808. /** Returns the midi beat-number of a song-position-pointer message.
  30809. @see isSongPositionPointer, songPositionPointer
  30810. */
  30811. int getSongPositionPointerMidiBeat() const noexcept;
  30812. /** Creates a song-position-pointer message.
  30813. The position is a number of midi beats from the start of the song, where 1 midi
  30814. beat is 6 midi clocks, and there are 24 midi clocks in a quarter-note. So there
  30815. are 4 midi beats in a quarter-note.
  30816. @see isSongPositionPointer, getSongPositionPointerMidiBeat
  30817. */
  30818. static MidiMessage songPositionPointer (int positionInMidiBeats) noexcept;
  30819. /** Returns true if this is a quarter-frame midi timecode message.
  30820. @see quarterFrame, getQuarterFrameSequenceNumber, getQuarterFrameValue
  30821. */
  30822. bool isQuarterFrame() const noexcept;
  30823. /** Returns the sequence number of a quarter-frame midi timecode message.
  30824. This will be a value between 0 and 7.
  30825. @see isQuarterFrame, getQuarterFrameValue, quarterFrame
  30826. */
  30827. int getQuarterFrameSequenceNumber() const noexcept;
  30828. /** Returns the value from a quarter-frame message.
  30829. This will be the lower nybble of the message's data-byte, a value
  30830. between 0 and 15
  30831. */
  30832. int getQuarterFrameValue() const noexcept;
  30833. /** Creates a quarter-frame MTC message.
  30834. @param sequenceNumber a value 0 to 7 for the upper nybble of the message's data byte
  30835. @param value a value 0 to 15 for the lower nybble of the message's data byte
  30836. */
  30837. static MidiMessage quarterFrame (int sequenceNumber, int value) noexcept;
  30838. /** SMPTE timecode types.
  30839. Used by the getFullFrameParameters() and fullFrame() methods.
  30840. */
  30841. enum SmpteTimecodeType
  30842. {
  30843. fps24 = 0,
  30844. fps25 = 1,
  30845. fps30drop = 2,
  30846. fps30 = 3
  30847. };
  30848. /** Returns true if this is a full-frame midi timecode message.
  30849. */
  30850. bool isFullFrame() const noexcept;
  30851. /** Extracts the timecode information from a full-frame midi timecode message.
  30852. You should only call this on messages where you've used isFullFrame() to
  30853. check that they're the right kind.
  30854. */
  30855. void getFullFrameParameters (int& hours,
  30856. int& minutes,
  30857. int& seconds,
  30858. int& frames,
  30859. SmpteTimecodeType& timecodeType) const noexcept;
  30860. /** Creates a full-frame MTC message.
  30861. */
  30862. static MidiMessage fullFrame (int hours,
  30863. int minutes,
  30864. int seconds,
  30865. int frames,
  30866. SmpteTimecodeType timecodeType);
  30867. /** Types of MMC command.
  30868. @see isMidiMachineControlMessage, getMidiMachineControlCommand, midiMachineControlCommand
  30869. */
  30870. enum MidiMachineControlCommand
  30871. {
  30872. mmc_stop = 1,
  30873. mmc_play = 2,
  30874. mmc_deferredplay = 3,
  30875. mmc_fastforward = 4,
  30876. mmc_rewind = 5,
  30877. mmc_recordStart = 6,
  30878. mmc_recordStop = 7,
  30879. mmc_pause = 9
  30880. };
  30881. /** Checks whether this is an MMC message.
  30882. If it is, you can use the getMidiMachineControlCommand() to find out its type.
  30883. */
  30884. bool isMidiMachineControlMessage() const noexcept;
  30885. /** For an MMC message, this returns its type.
  30886. Make sure it's actually an MMC message with isMidiMachineControlMessage() before
  30887. calling this method.
  30888. */
  30889. MidiMachineControlCommand getMidiMachineControlCommand() const noexcept;
  30890. /** Creates an MMC message.
  30891. */
  30892. static MidiMessage midiMachineControlCommand (MidiMachineControlCommand command);
  30893. /** Checks whether this is an MMC "goto" message.
  30894. If it is, the parameters passed-in are set to the time that the message contains.
  30895. @see midiMachineControlGoto
  30896. */
  30897. bool isMidiMachineControlGoto (int& hours,
  30898. int& minutes,
  30899. int& seconds,
  30900. int& frames) const noexcept;
  30901. /** Creates an MMC "goto" message.
  30902. This messages tells the device to go to a specific frame.
  30903. @see isMidiMachineControlGoto
  30904. */
  30905. static MidiMessage midiMachineControlGoto (int hours,
  30906. int minutes,
  30907. int seconds,
  30908. int frames);
  30909. /** Creates a master-volume change message.
  30910. @param volume the volume, 0 to 1.0
  30911. */
  30912. static MidiMessage masterVolume (float volume);
  30913. /** Creates a system-exclusive message.
  30914. The data passed in is wrapped with header and tail bytes of 0xf0 and 0xf7.
  30915. */
  30916. static MidiMessage createSysExMessage (const uint8* sysexData,
  30917. int dataSize);
  30918. /** Reads a midi variable-length integer.
  30919. @param data the data to read the number from
  30920. @param numBytesUsed on return, this will be set to the number of bytes that were read
  30921. */
  30922. static int readVariableLengthVal (const uint8* data,
  30923. int& numBytesUsed) noexcept;
  30924. /** Based on the first byte of a short midi message, this uses a lookup table
  30925. to return the message length (either 1, 2, or 3 bytes).
  30926. The value passed in must be 0x80 or higher.
  30927. */
  30928. static int getMessageLengthFromFirstByte (const uint8 firstByte) noexcept;
  30929. /** Returns the name of a midi note number.
  30930. E.g "C", "D#", etc.
  30931. @param noteNumber the midi note number, 0 to 127
  30932. @param useSharps if true, sharpened notes are used, e.g. "C#", otherwise
  30933. they'll be flattened, e.g. "Db"
  30934. @param includeOctaveNumber if true, the octave number will be appended to the string,
  30935. e.g. "C#4"
  30936. @param octaveNumForMiddleC if an octave number is being appended, this indicates the
  30937. number that will be used for middle C's octave
  30938. @see getMidiNoteInHertz
  30939. */
  30940. static String getMidiNoteName (int noteNumber,
  30941. bool useSharps,
  30942. bool includeOctaveNumber,
  30943. int octaveNumForMiddleC);
  30944. /** Returns the frequency of a midi note number.
  30945. The frequencyOfA parameter is an optional frequency for 'A', normally 440-444Hz for concert pitch.
  30946. @see getMidiNoteName
  30947. */
  30948. static const double getMidiNoteInHertz (int noteNumber, const double frequencyOfA = 440.0) noexcept;
  30949. /** Returns the standard name of a GM instrument.
  30950. @param midiInstrumentNumber the program number 0 to 127
  30951. @see getProgramChangeNumber
  30952. */
  30953. static String getGMInstrumentName (int midiInstrumentNumber);
  30954. /** Returns the name of a bank of GM instruments.
  30955. @param midiBankNumber the bank, 0 to 15
  30956. */
  30957. static String getGMInstrumentBankName (int midiBankNumber);
  30958. /** Returns the standard name of a channel 10 percussion sound.
  30959. @param midiNoteNumber the key number, 35 to 81
  30960. */
  30961. static String getRhythmInstrumentName (int midiNoteNumber);
  30962. /** Returns the name of a controller type number.
  30963. @see getControllerNumber
  30964. */
  30965. static String getControllerName (int controllerNumber);
  30966. private:
  30967. double timeStamp;
  30968. uint8* data;
  30969. int size;
  30970. #ifndef DOXYGEN
  30971. union
  30972. {
  30973. uint8 asBytes[4];
  30974. uint32 asInt32;
  30975. } preallocatedData;
  30976. #endif
  30977. };
  30978. #endif // __JUCE_MIDIMESSAGE_JUCEHEADER__
  30979. /*** End of inlined file: juce_MidiMessage.h ***/
  30980. class MidiInput;
  30981. /**
  30982. Receives incoming messages from a physical MIDI input device.
  30983. This class is overridden to handle incoming midi messages. See the MidiInput
  30984. class for more details.
  30985. @see MidiInput
  30986. */
  30987. class JUCE_API MidiInputCallback
  30988. {
  30989. public:
  30990. /** Destructor. */
  30991. virtual ~MidiInputCallback() {}
  30992. /** Receives an incoming message.
  30993. A MidiInput object will call this method when a midi event arrives. It'll be
  30994. called on a high-priority system thread, so avoid doing anything time-consuming
  30995. in here, and avoid making any UI calls. You might find the MidiBuffer class helpful
  30996. for queueing incoming messages for use later.
  30997. @param source the MidiInput object that generated the message
  30998. @param message the incoming message. The message's timestamp is set to a value
  30999. equivalent to (Time::getMillisecondCounter() / 1000.0) to specify the
  31000. time when the message arrived.
  31001. */
  31002. virtual void handleIncomingMidiMessage (MidiInput* source,
  31003. const MidiMessage& message) = 0;
  31004. /** Notification sent each time a packet of a multi-packet sysex message arrives.
  31005. If a long sysex message is broken up into multiple packets, this callback is made
  31006. for each packet that arrives until the message is finished, at which point
  31007. the normal handleIncomingMidiMessage() callback will be made with the entire
  31008. message.
  31009. The message passed in will contain the start of a sysex, but won't be finished
  31010. with the terminating 0xf7 byte.
  31011. */
  31012. virtual void handlePartialSysexMessage (MidiInput* source,
  31013. const uint8* messageData,
  31014. const int numBytesSoFar,
  31015. const double timestamp)
  31016. {
  31017. // (this bit is just to avoid compiler warnings about unused variables)
  31018. (void) source; (void) messageData; (void) numBytesSoFar; (void) timestamp;
  31019. }
  31020. };
  31021. /**
  31022. Represents a midi input device.
  31023. To create one of these, use the static getDevices() method to find out what inputs are
  31024. available, and then use the openDevice() method to try to open one.
  31025. @see MidiOutput
  31026. */
  31027. class JUCE_API MidiInput
  31028. {
  31029. public:
  31030. /** Returns a list of the available midi input devices.
  31031. You can open one of the devices by passing its index into the
  31032. openDevice() method.
  31033. @see getDefaultDeviceIndex, openDevice
  31034. */
  31035. static StringArray getDevices();
  31036. /** Returns the index of the default midi input device to use.
  31037. This refers to the index in the list returned by getDevices().
  31038. */
  31039. static int getDefaultDeviceIndex();
  31040. /** Tries to open one of the midi input devices.
  31041. This will return a MidiInput object if it manages to open it. You can then
  31042. call start() and stop() on this device, and delete it when no longer needed.
  31043. If the device can't be opened, this will return a null pointer.
  31044. @param deviceIndex the index of a device from the list returned by getDevices()
  31045. @param callback the object that will receive the midi messages from this device.
  31046. @see MidiInputCallback, getDevices
  31047. */
  31048. static MidiInput* openDevice (int deviceIndex,
  31049. MidiInputCallback* callback);
  31050. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  31051. /** This will try to create a new midi input device (Not available on Windows).
  31052. This will attempt to create a new midi input device with the specified name,
  31053. for other apps to connect to.
  31054. Returns 0 if a device can't be created.
  31055. @param deviceName the name to use for the new device
  31056. @param callback the object that will receive the midi messages from this device.
  31057. */
  31058. static MidiInput* createNewDevice (const String& deviceName,
  31059. MidiInputCallback* callback);
  31060. #endif
  31061. /** Destructor. */
  31062. virtual ~MidiInput();
  31063. /** Returns the name of this device. */
  31064. const String& getName() const noexcept { return name; }
  31065. /** Allows you to set a custom name for the device, in case you don't like the name
  31066. it was given when created.
  31067. */
  31068. void setName (const String& newName) noexcept { name = newName; }
  31069. /** Starts the device running.
  31070. After calling this, the device will start sending midi messages to the
  31071. MidiInputCallback object that was specified when the openDevice() method
  31072. was called.
  31073. @see stop
  31074. */
  31075. virtual void start();
  31076. /** Stops the device running.
  31077. @see start
  31078. */
  31079. virtual void stop();
  31080. protected:
  31081. String name;
  31082. void* internal;
  31083. explicit MidiInput (const String& name);
  31084. private:
  31085. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInput);
  31086. };
  31087. #endif // __JUCE_MIDIINPUT_JUCEHEADER__
  31088. /*** End of inlined file: juce_MidiInput.h ***/
  31089. /*** Start of inlined file: juce_MidiOutput.h ***/
  31090. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  31091. #define __JUCE_MIDIOUTPUT_JUCEHEADER__
  31092. /*** Start of inlined file: juce_MidiBuffer.h ***/
  31093. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  31094. #define __JUCE_MIDIBUFFER_JUCEHEADER__
  31095. /**
  31096. Holds a sequence of time-stamped midi events.
  31097. Analogous to the AudioSampleBuffer, this holds a set of midi events with
  31098. integer time-stamps. The buffer is kept sorted in order of the time-stamps.
  31099. @see MidiMessage
  31100. */
  31101. class JUCE_API MidiBuffer
  31102. {
  31103. public:
  31104. /** Creates an empty MidiBuffer. */
  31105. MidiBuffer() noexcept;
  31106. /** Creates a MidiBuffer containing a single midi message. */
  31107. explicit MidiBuffer (const MidiMessage& message) noexcept;
  31108. /** Creates a copy of another MidiBuffer. */
  31109. MidiBuffer (const MidiBuffer& other) noexcept;
  31110. /** Makes a copy of another MidiBuffer. */
  31111. MidiBuffer& operator= (const MidiBuffer& other) noexcept;
  31112. /** Destructor */
  31113. ~MidiBuffer();
  31114. /** Removes all events from the buffer. */
  31115. void clear() noexcept;
  31116. /** Removes all events between two times from the buffer.
  31117. All events for which (start <= event position < start + numSamples) will
  31118. be removed.
  31119. */
  31120. void clear (int start, int numSamples);
  31121. /** Returns true if the buffer is empty.
  31122. To actually retrieve the events, use a MidiBuffer::Iterator object
  31123. */
  31124. bool isEmpty() const noexcept;
  31125. /** Counts the number of events in the buffer.
  31126. This is actually quite a slow operation, as it has to iterate through all
  31127. the events, so you might prefer to call isEmpty() if that's all you need
  31128. to know.
  31129. */
  31130. int getNumEvents() const noexcept;
  31131. /** Adds an event to the buffer.
  31132. The sample number will be used to determine the position of the event in
  31133. the buffer, which is always kept sorted. The MidiMessage's timestamp is
  31134. ignored.
  31135. If an event is added whose sample position is the same as one or more events
  31136. already in the buffer, the new event will be placed after the existing ones.
  31137. To retrieve events, use a MidiBuffer::Iterator object
  31138. */
  31139. void addEvent (const MidiMessage& midiMessage, int sampleNumber);
  31140. /** Adds an event to the buffer from raw midi data.
  31141. The sample number will be used to determine the position of the event in
  31142. the buffer, which is always kept sorted.
  31143. If an event is added whose sample position is the same as one or more events
  31144. already in the buffer, the new event will be placed after the existing ones.
  31145. The event data will be inspected to calculate the number of bytes in length that
  31146. the midi event really takes up, so maxBytesOfMidiData may be longer than the data
  31147. that actually gets stored. E.g. if you pass in a note-on and a length of 4 bytes,
  31148. it'll actually only store 3 bytes. If the midi data is invalid, it might not
  31149. add an event at all.
  31150. To retrieve events, use a MidiBuffer::Iterator object
  31151. */
  31152. void addEvent (const void* rawMidiData,
  31153. int maxBytesOfMidiData,
  31154. int sampleNumber);
  31155. /** Adds some events from another buffer to this one.
  31156. @param otherBuffer the buffer containing the events you want to add
  31157. @param startSample the lowest sample number in the source buffer for which
  31158. events should be added. Any source events whose timestamp is
  31159. less than this will be ignored
  31160. @param numSamples the valid range of samples from the source buffer for which
  31161. events should be added - i.e. events in the source buffer whose
  31162. timestamp is greater than or equal to (startSample + numSamples)
  31163. will be ignored. If this value is less than 0, all events after
  31164. startSample will be taken.
  31165. @param sampleDeltaToAdd a value which will be added to the source timestamps of the events
  31166. that are added to this buffer
  31167. */
  31168. void addEvents (const MidiBuffer& otherBuffer,
  31169. int startSample,
  31170. int numSamples,
  31171. int sampleDeltaToAdd);
  31172. /** Returns the sample number of the first event in the buffer.
  31173. If the buffer's empty, this will just return 0.
  31174. */
  31175. int getFirstEventTime() const noexcept;
  31176. /** Returns the sample number of the last event in the buffer.
  31177. If the buffer's empty, this will just return 0.
  31178. */
  31179. int getLastEventTime() const noexcept;
  31180. /** Exchanges the contents of this buffer with another one.
  31181. This is a quick operation, because no memory allocating or copying is done, it
  31182. just swaps the internal state of the two buffers.
  31183. */
  31184. void swapWith (MidiBuffer& other) noexcept;
  31185. /** Preallocates some memory for the buffer to use.
  31186. This helps to avoid needing to reallocate space when the buffer has messages
  31187. added to it.
  31188. */
  31189. void ensureSize (size_t minimumNumBytes);
  31190. /**
  31191. Used to iterate through the events in a MidiBuffer.
  31192. Note that altering the buffer while an iterator is using it isn't a
  31193. safe operation.
  31194. @see MidiBuffer
  31195. */
  31196. class JUCE_API Iterator
  31197. {
  31198. public:
  31199. /** Creates an Iterator for this MidiBuffer. */
  31200. Iterator (const MidiBuffer& buffer) noexcept;
  31201. /** Destructor. */
  31202. ~Iterator() noexcept;
  31203. /** Repositions the iterator so that the next event retrieved will be the first
  31204. one whose sample position is at greater than or equal to the given position.
  31205. */
  31206. void setNextSamplePosition (int samplePosition) noexcept;
  31207. /** Retrieves a copy of the next event from the buffer.
  31208. @param result on return, this will be the message (the MidiMessage's timestamp
  31209. is not set)
  31210. @param samplePosition on return, this will be the position of the event
  31211. @returns true if an event was found, or false if the iterator has reached
  31212. the end of the buffer
  31213. */
  31214. bool getNextEvent (MidiMessage& result,
  31215. int& samplePosition) noexcept;
  31216. /** Retrieves the next event from the buffer.
  31217. @param midiData on return, this pointer will be set to a block of data containing
  31218. the midi message. Note that to make it fast, this is a pointer
  31219. directly into the MidiBuffer's internal data, so is only valid
  31220. temporarily until the MidiBuffer is altered.
  31221. @param numBytesOfMidiData on return, this is the number of bytes of data used by the
  31222. midi message
  31223. @param samplePosition on return, this will be the position of the event
  31224. @returns true if an event was found, or false if the iterator has reached
  31225. the end of the buffer
  31226. */
  31227. bool getNextEvent (const uint8* &midiData,
  31228. int& numBytesOfMidiData,
  31229. int& samplePosition) noexcept;
  31230. private:
  31231. const MidiBuffer& buffer;
  31232. const uint8* data;
  31233. JUCE_DECLARE_NON_COPYABLE (Iterator);
  31234. };
  31235. private:
  31236. friend class MidiBuffer::Iterator;
  31237. MemoryBlock data;
  31238. int bytesUsed;
  31239. uint8* getData() const noexcept;
  31240. uint8* findEventAfter (uint8* d, int samplePosition) const noexcept;
  31241. static int getEventTime (const void* d) noexcept;
  31242. static uint16 getEventDataSize (const void* d) noexcept;
  31243. static uint16 getEventTotalSize (const void* d) noexcept;
  31244. JUCE_LEAK_DETECTOR (MidiBuffer);
  31245. };
  31246. #endif // __JUCE_MIDIBUFFER_JUCEHEADER__
  31247. /*** End of inlined file: juce_MidiBuffer.h ***/
  31248. /**
  31249. Controls a physical MIDI output device.
  31250. To create one of these, use the static getDevices() method to get a list of the
  31251. available output devices, then use the openDevice() method to try to open one.
  31252. @see MidiInput
  31253. */
  31254. class JUCE_API MidiOutput : private Thread
  31255. {
  31256. public:
  31257. /** Returns a list of the available midi output devices.
  31258. You can open one of the devices by passing its index into the
  31259. openDevice() method.
  31260. @see getDefaultDeviceIndex, openDevice
  31261. */
  31262. static StringArray getDevices();
  31263. /** Returns the index of the default midi output device to use.
  31264. This refers to the index in the list returned by getDevices().
  31265. */
  31266. static int getDefaultDeviceIndex();
  31267. /** Tries to open one of the midi output devices.
  31268. This will return a MidiOutput object if it manages to open it. You can then
  31269. send messages to this device, and delete it when no longer needed.
  31270. If the device can't be opened, this will return a null pointer.
  31271. @param deviceIndex the index of a device from the list returned by getDevices()
  31272. @see getDevices
  31273. */
  31274. static MidiOutput* openDevice (int deviceIndex);
  31275. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  31276. /** This will try to create a new midi output device (Not available on Windows).
  31277. This will attempt to create a new midi output device that other apps can connect
  31278. to and use as their midi input.
  31279. Returns 0 if a device can't be created.
  31280. @param deviceName the name to use for the new device
  31281. */
  31282. static MidiOutput* createNewDevice (const String& deviceName);
  31283. #endif
  31284. /** Destructor. */
  31285. virtual ~MidiOutput();
  31286. /** Makes this device output a midi message.
  31287. @see MidiMessage
  31288. */
  31289. virtual void sendMessageNow (const MidiMessage& message);
  31290. /** This lets you supply a block of messages that will be sent out at some point
  31291. in the future.
  31292. The MidiOutput class has an internal thread that can send out timestamped
  31293. messages - this appends a set of messages to its internal buffer, ready for
  31294. sending.
  31295. This will only work if you've already started the thread with startBackgroundThread().
  31296. A time is supplied, at which the block of messages should be sent. This time uses
  31297. the same time base as Time::getMillisecondCounter(), and must be in the future.
  31298. The samplesPerSecondForBuffer parameter indicates the number of samples per second
  31299. used by the MidiBuffer. Each event in a MidiBuffer has a sample position, and the
  31300. samplesPerSecondForBuffer value is needed to convert this sample position to a
  31301. real time.
  31302. */
  31303. virtual void sendBlockOfMessages (const MidiBuffer& buffer,
  31304. double millisecondCounterToStartAt,
  31305. double samplesPerSecondForBuffer);
  31306. /** Gets rid of any midi messages that had been added by sendBlockOfMessages().
  31307. */
  31308. virtual void clearAllPendingMessages();
  31309. /** Starts up a background thread so that the device can send blocks of data.
  31310. Call this to get the device ready, before using sendBlockOfMessages().
  31311. */
  31312. virtual void startBackgroundThread();
  31313. /** Stops the background thread, and clears any pending midi events.
  31314. @see startBackgroundThread
  31315. */
  31316. virtual void stopBackgroundThread();
  31317. protected:
  31318. void* internal;
  31319. CriticalSection lock;
  31320. struct PendingMessage;
  31321. PendingMessage* firstMessage;
  31322. MidiOutput();
  31323. void run();
  31324. private:
  31325. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiOutput);
  31326. };
  31327. #endif // __JUCE_MIDIOUTPUT_JUCEHEADER__
  31328. /*** End of inlined file: juce_MidiOutput.h ***/
  31329. /**
  31330. Manages the state of some audio and midi i/o devices.
  31331. This class keeps tracks of a currently-selected audio device, through
  31332. with which it continuously streams data from an audio callback, as well as
  31333. one or more midi inputs.
  31334. The idea is that your application will create one global instance of this object,
  31335. and let it take care of creating and deleting specific types of audio devices
  31336. internally. So when the device is changed, your callbacks will just keep running
  31337. without having to worry about this.
  31338. The manager can save and reload all of its device settings as XML, which
  31339. makes it very easy for you to save and reload the audio setup of your
  31340. application.
  31341. And to make it easy to let the user change its settings, there's a component
  31342. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  31343. device selection/sample-rate/latency controls.
  31344. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  31345. call addAudioCallback() to register your audio callback with it, and use that to process
  31346. your audio data.
  31347. The manager also acts as a handy hub for incoming midi messages, allowing a
  31348. listener to register for messages from either a specific midi device, or from whatever
  31349. the current default midi input device is. The listener then doesn't have to worry about
  31350. re-registering with different midi devices if they are changed or deleted.
  31351. And yet another neat trick is that amount of CPU time being used is measured and
  31352. available with the getCpuUsage() method.
  31353. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  31354. listeners whenever one of its settings is changed.
  31355. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  31356. */
  31357. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  31358. {
  31359. public:
  31360. /** Creates a default AudioDeviceManager.
  31361. Initially no audio device will be selected. You should call the initialise() method
  31362. and register an audio callback with setAudioCallback() before it'll be able to
  31363. actually make any noise.
  31364. */
  31365. AudioDeviceManager();
  31366. /** Destructor. */
  31367. ~AudioDeviceManager();
  31368. /**
  31369. This structure holds a set of properties describing the current audio setup.
  31370. An AudioDeviceManager uses this class to save/load its current settings, and to
  31371. specify your preferred options when opening a device.
  31372. @see AudioDeviceManager::setAudioDeviceSetup(), AudioDeviceManager::initialise()
  31373. */
  31374. struct JUCE_API AudioDeviceSetup
  31375. {
  31376. /** Creates an AudioDeviceSetup object.
  31377. The default constructor sets all the member variables to indicate default values.
  31378. You can then fill-in any values you want to before passing the object to
  31379. AudioDeviceManager::initialise().
  31380. */
  31381. AudioDeviceSetup();
  31382. bool operator== (const AudioDeviceSetup& other) const;
  31383. /** The name of the audio device used for output.
  31384. The name has to be one of the ones listed by the AudioDeviceManager's currently
  31385. selected device type.
  31386. This may be the same as the input device.
  31387. An empty string indicates the default device.
  31388. */
  31389. String outputDeviceName;
  31390. /** The name of the audio device used for input.
  31391. This may be the same as the output device.
  31392. An empty string indicates the default device.
  31393. */
  31394. String inputDeviceName;
  31395. /** The current sample rate.
  31396. This rate is used for both the input and output devices.
  31397. A value of 0 indicates the default rate.
  31398. */
  31399. double sampleRate;
  31400. /** The buffer size, in samples.
  31401. This buffer size is used for both the input and output devices.
  31402. A value of 0 indicates the default buffer size.
  31403. */
  31404. int bufferSize;
  31405. /** The set of active input channels.
  31406. The bits that are set in this array indicate the channels of the
  31407. input device that are active.
  31408. If useDefaultInputChannels is true, this value is ignored.
  31409. */
  31410. BigInteger inputChannels;
  31411. /** If this is true, it indicates that the inputChannels array
  31412. should be ignored, and instead, the device's default channels
  31413. should be used.
  31414. */
  31415. bool useDefaultInputChannels;
  31416. /** The set of active output channels.
  31417. The bits that are set in this array indicate the channels of the
  31418. input device that are active.
  31419. If useDefaultOutputChannels is true, this value is ignored.
  31420. */
  31421. BigInteger outputChannels;
  31422. /** If this is true, it indicates that the outputChannels array
  31423. should be ignored, and instead, the device's default channels
  31424. should be used.
  31425. */
  31426. bool useDefaultOutputChannels;
  31427. };
  31428. /** Opens a set of audio devices ready for use.
  31429. This will attempt to open either a default audio device, or one that was
  31430. previously saved as XML.
  31431. @param numInputChannelsNeeded a minimum number of input channels needed
  31432. by your app.
  31433. @param numOutputChannelsNeeded a minimum number of output channels to open
  31434. @param savedState either a previously-saved state that was produced
  31435. by createStateXml(), or 0 if you want the manager
  31436. to choose the best device to open.
  31437. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  31438. fails to open, then a default device will be used
  31439. instead. If false, then on failure, no device is
  31440. opened.
  31441. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  31442. name, then that will be used as the default device
  31443. (assuming that there wasn't one specified in the XML).
  31444. The string can actually be a simple wildcard, containing "*"
  31445. and "?" characters
  31446. @param preferredSetupOptions if this is non-null, the structure will be used as the
  31447. set of preferred settings when opening the device. If you
  31448. use this parameter, the preferredDefaultDeviceName
  31449. field will be ignored
  31450. @returns an error message if anything went wrong, or an empty string if it worked ok.
  31451. */
  31452. String initialise (int numInputChannelsNeeded,
  31453. int numOutputChannelsNeeded,
  31454. const XmlElement* savedState,
  31455. bool selectDefaultDeviceOnFailure,
  31456. const String& preferredDefaultDeviceName = String::empty,
  31457. const AudioDeviceSetup* preferredSetupOptions = 0);
  31458. /** Returns some XML representing the current state of the manager.
  31459. This stores the current device, its samplerate, block size, etc, and
  31460. can be restored later with initialise().
  31461. Note that this can return a null pointer if no settings have been explicitly changed
  31462. (i.e. if the device manager has just been left in its default state).
  31463. */
  31464. XmlElement* createStateXml() const;
  31465. /** Returns the current device properties that are in use.
  31466. @see setAudioDeviceSetup
  31467. */
  31468. void getAudioDeviceSetup (AudioDeviceSetup& setup);
  31469. /** Changes the current device or its settings.
  31470. If you want to change a device property, like the current sample rate or
  31471. block size, you can call getAudioDeviceSetup() to retrieve the current
  31472. settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
  31473. and pass it back into this method to apply the new settings.
  31474. @param newSetup the settings that you'd like to use
  31475. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  31476. settings will be taken as having been explicitly chosen by the
  31477. user, and the next time createStateXml() is called, these settings
  31478. will be returned. If it's false, then the device is treated as a
  31479. temporary or default device, and a call to createStateXml() will
  31480. return either the last settings that were made with treatAsChosenDevice
  31481. as true, or the last XML settings that were passed into initialise().
  31482. @returns an error message if anything went wrong, or an empty string if it worked ok.
  31483. @see getAudioDeviceSetup
  31484. */
  31485. String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  31486. bool treatAsChosenDevice);
  31487. /** Returns the currently-active audio device. */
  31488. AudioIODevice* getCurrentAudioDevice() const noexcept { return currentAudioDevice; }
  31489. /** Returns the type of audio device currently in use.
  31490. @see setCurrentAudioDeviceType
  31491. */
  31492. String getCurrentAudioDeviceType() const { return currentDeviceType; }
  31493. /** Returns the currently active audio device type object.
  31494. Don't keep a copy of this pointer - it's owned by the device manager and could
  31495. change at any time.
  31496. */
  31497. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  31498. /** Changes the class of audio device being used.
  31499. This switches between, e.g. ASIO and DirectSound. On the Mac you probably won't ever call
  31500. this because there's only one type: CoreAudio.
  31501. For a list of types, see getAvailableDeviceTypes().
  31502. */
  31503. void setCurrentAudioDeviceType (const String& type,
  31504. bool treatAsChosenDevice);
  31505. /** Closes the currently-open device.
  31506. You can call restartLastAudioDevice() later to reopen it in the same state
  31507. that it was just in.
  31508. */
  31509. void closeAudioDevice();
  31510. /** Tries to reload the last audio device that was running.
  31511. Note that this only reloads the last device that was running before
  31512. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  31513. and can only be called after a device has been opened with SetAudioDevice().
  31514. If a device is already open, this call will do nothing.
  31515. */
  31516. void restartLastAudioDevice();
  31517. /** Registers an audio callback to be used.
  31518. The manager will redirect callbacks from whatever audio device is currently
  31519. in use to all registered callback objects. If more than one callback is
  31520. active, they will all be given the same input data, and their outputs will
  31521. be summed.
  31522. If necessary, this method will invoke audioDeviceAboutToStart() on the callback
  31523. object before returning.
  31524. To remove a callback, use removeAudioCallback().
  31525. */
  31526. void addAudioCallback (AudioIODeviceCallback* newCallback);
  31527. /** Deregisters a previously added callback.
  31528. If necessary, this method will invoke audioDeviceStopped() on the callback
  31529. object before returning.
  31530. @see addAudioCallback
  31531. */
  31532. void removeAudioCallback (AudioIODeviceCallback* callback);
  31533. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  31534. Returns a value between 0 and 1.0
  31535. */
  31536. double getCpuUsage() const;
  31537. /** Enables or disables a midi input device.
  31538. The list of devices can be obtained with the MidiInput::getDevices() method.
  31539. Any incoming messages from enabled input devices will be forwarded on to all the
  31540. listeners that have been registered with the addMidiInputCallback() method. They
  31541. can either register for messages from a particular device, or from just the
  31542. "default" midi input.
  31543. Routing the midi input via an AudioDeviceManager means that when a listener
  31544. registers for the default midi input, this default device can be changed by the
  31545. manager without the listeners having to know about it or re-register.
  31546. It also means that a listener can stay registered for a midi input that is disabled
  31547. or not present, so that when the input is re-enabled, the listener will start
  31548. receiving messages again.
  31549. @see addMidiInputCallback, isMidiInputEnabled
  31550. */
  31551. void setMidiInputEnabled (const String& midiInputDeviceName, bool enabled);
  31552. /** Returns true if a given midi input device is being used.
  31553. @see setMidiInputEnabled
  31554. */
  31555. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  31556. /** Registers a listener for callbacks when midi events arrive from a midi input.
  31557. The device name can be empty to indicate that it wants events from whatever the
  31558. current "default" device is. Or it can be the name of one of the midi input devices
  31559. (see MidiInput::getDevices() for the names).
  31560. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  31561. events forwarded on to listeners.
  31562. */
  31563. void addMidiInputCallback (const String& midiInputDeviceName,
  31564. MidiInputCallback* callback);
  31565. /** Removes a listener that was previously registered with addMidiInputCallback().
  31566. */
  31567. void removeMidiInputCallback (const String& midiInputDeviceName,
  31568. MidiInputCallback* callback);
  31569. /** Sets a midi output device to use as the default.
  31570. The list of devices can be obtained with the MidiOutput::getDevices() method.
  31571. The specified device will be opened automatically and can be retrieved with the
  31572. getDefaultMidiOutput() method.
  31573. Pass in an empty string to deselect all devices. For the default device, you
  31574. can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  31575. @see getDefaultMidiOutput, getDefaultMidiOutputName
  31576. */
  31577. void setDefaultMidiOutput (const String& deviceName);
  31578. /** Returns the name of the default midi output.
  31579. @see setDefaultMidiOutput, getDefaultMidiOutput
  31580. */
  31581. String getDefaultMidiOutputName() const { return defaultMidiOutputName; }
  31582. /** Returns the current default midi output device.
  31583. If no device has been selected, or the device can't be opened, this will
  31584. return 0.
  31585. @see getDefaultMidiOutputName
  31586. */
  31587. MidiOutput* getDefaultMidiOutput() const noexcept { return defaultMidiOutput; }
  31588. /** Returns a list of the types of device supported.
  31589. */
  31590. const OwnedArray <AudioIODeviceType>& getAvailableDeviceTypes();
  31591. /** Creates a list of available types.
  31592. This will add a set of new AudioIODeviceType objects to the specified list, to
  31593. represent each available types of device.
  31594. You can override this if your app needs to do something specific, like avoid
  31595. using DirectSound devices, etc.
  31596. */
  31597. virtual void createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& types);
  31598. /** Plays a beep through the current audio device.
  31599. This is here to allow the audio setup UI panels to easily include a "test"
  31600. button so that the user can check where the audio is coming from.
  31601. */
  31602. void playTestSound();
  31603. /** Turns on level-measuring.
  31604. When enabled, the device manager will measure the peak input level
  31605. across all channels, and you can get this level by calling getCurrentInputLevel().
  31606. This is mainly intended for audio setup UI panels to use to create a mic
  31607. level display, so that the user can check that they've selected the right
  31608. device.
  31609. A simple filter is used to make the level decay smoothly, but this is
  31610. only intended for giving rough feedback, and not for any kind of accurate
  31611. measurement.
  31612. */
  31613. void enableInputLevelMeasurement (bool enableMeasurement);
  31614. /** Returns the current input level.
  31615. To use this, you must first enable it by calling enableInputLevelMeasurement().
  31616. See enableInputLevelMeasurement() for more info.
  31617. */
  31618. double getCurrentInputLevel() const;
  31619. /** Returns the a lock that can be used to synchronise access to the audio callback.
  31620. Obviously while this is locked, you're blocking the audio thread from running, so
  31621. it must only be used for very brief periods when absolutely necessary.
  31622. */
  31623. CriticalSection& getAudioCallbackLock() noexcept { return audioCallbackLock; }
  31624. /** Returns the a lock that can be used to synchronise access to the midi callback.
  31625. Obviously while this is locked, you're blocking the midi system from running, so
  31626. it must only be used for very brief periods when absolutely necessary.
  31627. */
  31628. CriticalSection& getMidiCallbackLock() noexcept { return midiCallbackLock; }
  31629. private:
  31630. OwnedArray <AudioIODeviceType> availableDeviceTypes;
  31631. OwnedArray <AudioDeviceSetup> lastDeviceTypeConfigs;
  31632. AudioDeviceSetup currentSetup;
  31633. ScopedPointer <AudioIODevice> currentAudioDevice;
  31634. Array <AudioIODeviceCallback*> callbacks;
  31635. int numInputChansNeeded, numOutputChansNeeded;
  31636. String currentDeviceType;
  31637. BigInteger inputChannels, outputChannels;
  31638. ScopedPointer <XmlElement> lastExplicitSettings;
  31639. mutable bool listNeedsScanning;
  31640. bool useInputNames;
  31641. int inputLevelMeasurementEnabledCount;
  31642. double inputLevel;
  31643. ScopedPointer <AudioSampleBuffer> testSound;
  31644. int testSoundPosition;
  31645. AudioSampleBuffer tempBuffer;
  31646. StringArray midiInsFromXml;
  31647. OwnedArray <MidiInput> enabledMidiInputs;
  31648. Array <MidiInputCallback*> midiCallbacks;
  31649. StringArray midiCallbackDevices;
  31650. String defaultMidiOutputName;
  31651. ScopedPointer <MidiOutput> defaultMidiOutput;
  31652. CriticalSection audioCallbackLock, midiCallbackLock;
  31653. double cpuUsageMs, timeToCpuScale;
  31654. class CallbackHandler : public AudioIODeviceCallback,
  31655. public MidiInputCallback,
  31656. public AudioIODeviceType::Listener
  31657. {
  31658. public:
  31659. void audioDeviceIOCallback (const float**, int, float**, int, int);
  31660. void audioDeviceAboutToStart (AudioIODevice*);
  31661. void audioDeviceStopped();
  31662. void handleIncomingMidiMessage (MidiInput*, const MidiMessage&);
  31663. void audioDeviceListChanged();
  31664. AudioDeviceManager* owner;
  31665. };
  31666. CallbackHandler callbackHandler;
  31667. friend class CallbackHandler;
  31668. void audioDeviceIOCallbackInt (const float** inputChannelData, int totalNumInputChannels,
  31669. float** outputChannelData, int totalNumOutputChannels, int numSamples);
  31670. void audioDeviceAboutToStartInt (AudioIODevice*);
  31671. void audioDeviceStoppedInt();
  31672. void handleIncomingMidiMessageInt (MidiInput*, const MidiMessage&);
  31673. void audioDeviceListChanged();
  31674. String restartDevice (int blockSizeToUse, double sampleRateToUse,
  31675. const BigInteger& ins, const BigInteger& outs);
  31676. void stopDevice();
  31677. void updateXml();
  31678. void createDeviceTypesIfNeeded();
  31679. void scanDevicesIfNeeded();
  31680. void deleteCurrentDevice();
  31681. double chooseBestSampleRate (double preferred) const;
  31682. int chooseBestBufferSize (int preferred) const;
  31683. void insertDefaultDeviceNames (AudioDeviceSetup&) const;
  31684. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  31685. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceManager);
  31686. };
  31687. #endif // __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  31688. /*** End of inlined file: juce_AudioDeviceManager.h ***/
  31689. #endif
  31690. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  31691. #endif
  31692. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  31693. #endif
  31694. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  31695. #endif
  31696. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  31697. #endif
  31698. #ifndef __JUCE_DECIBELS_JUCEHEADER__
  31699. /*** Start of inlined file: juce_Decibels.h ***/
  31700. #ifndef __JUCE_DECIBELS_JUCEHEADER__
  31701. #define __JUCE_DECIBELS_JUCEHEADER__
  31702. /**
  31703. This class contains some helpful static methods for dealing with decibel values.
  31704. */
  31705. class Decibels
  31706. {
  31707. public:
  31708. /** Converts a dBFS value to its equivalent gain level.
  31709. A gain of 1.0 = 0 dB, and lower gains map onto negative decibel values. Any
  31710. decibel value lower than minusInfinityDb will return a gain of 0.
  31711. */
  31712. template <typename Type>
  31713. static Type decibelsToGain (const Type decibels,
  31714. const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
  31715. {
  31716. return decibels > minusInfinityDb ? powf ((Type) 10.0, decibels * (Type) 0.05)
  31717. : Type();
  31718. }
  31719. /** Converts a gain level into a dBFS value.
  31720. A gain of 1.0 = 0 dB, and lower gains map onto negative decibel values.
  31721. If the gain is 0 (or negative), then the method will return the value
  31722. provided as minusInfinityDb.
  31723. */
  31724. template <typename Type>
  31725. static Type gainToDecibels (const Type gain,
  31726. const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
  31727. {
  31728. return gain > Type() ? jmax (minusInfinityDb, (Type) std::log10 (gain) * (Type) 20.0)
  31729. : minusInfinityDb;
  31730. }
  31731. /** Converts a decibel reading to a string, with the 'dB' suffix.
  31732. If the decibel value is lower than minusInfinityDb, the return value will
  31733. be "-INF dB".
  31734. */
  31735. template <typename Type>
  31736. static String toString (const Type decibels,
  31737. const int decimalPlaces = 2,
  31738. const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
  31739. {
  31740. String s;
  31741. if (decibels <= minusInfinityDb)
  31742. {
  31743. s = "-INF dB";
  31744. }
  31745. else
  31746. {
  31747. if (decibels >= Type())
  31748. s << '+';
  31749. s << String (decibels, decimalPlaces) << " dB";
  31750. }
  31751. return s;
  31752. }
  31753. private:
  31754. enum
  31755. {
  31756. defaultMinusInfinitydB = -100
  31757. };
  31758. Decibels(); // This class can't be instantiated, it's just a holder for static methods..
  31759. JUCE_DECLARE_NON_COPYABLE (Decibels);
  31760. };
  31761. #endif // __JUCE_DECIBELS_JUCEHEADER__
  31762. /*** End of inlined file: juce_Decibels.h ***/
  31763. #endif
  31764. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  31765. #endif
  31766. #ifndef __JUCE_REVERB_JUCEHEADER__
  31767. #endif
  31768. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  31769. #endif
  31770. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  31771. /*** Start of inlined file: juce_MidiFile.h ***/
  31772. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  31773. #define __JUCE_MIDIFILE_JUCEHEADER__
  31774. /*** Start of inlined file: juce_MidiMessageSequence.h ***/
  31775. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  31776. #define __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  31777. /**
  31778. A sequence of timestamped midi messages.
  31779. This allows the sequence to be manipulated, and also to be read from and
  31780. written to a standard midi file.
  31781. @see MidiMessage, MidiFile
  31782. */
  31783. class JUCE_API MidiMessageSequence
  31784. {
  31785. public:
  31786. /** Creates an empty midi sequence object. */
  31787. MidiMessageSequence();
  31788. /** Creates a copy of another sequence. */
  31789. MidiMessageSequence (const MidiMessageSequence& other);
  31790. /** Replaces this sequence with another one. */
  31791. MidiMessageSequence& operator= (const MidiMessageSequence& other);
  31792. /** Destructor. */
  31793. ~MidiMessageSequence();
  31794. /** Structure used to hold midi events in the sequence.
  31795. These structures act as 'handles' on the events as they are moved about in
  31796. the list, and make it quick to find the matching note-offs for note-on events.
  31797. @see MidiMessageSequence::getEventPointer
  31798. */
  31799. class MidiEventHolder
  31800. {
  31801. public:
  31802. /** Destructor. */
  31803. ~MidiEventHolder();
  31804. /** The message itself, whose timestamp is used to specify the event's time.
  31805. */
  31806. MidiMessage message;
  31807. /** The matching note-off event (if this is a note-on event).
  31808. If this isn't a note-on, this pointer will be null.
  31809. Use the MidiMessageSequence::updateMatchedPairs() method to keep these
  31810. note-offs up-to-date after events have been moved around in the sequence
  31811. or deleted.
  31812. */
  31813. MidiEventHolder* noteOffObject;
  31814. private:
  31815. friend class MidiMessageSequence;
  31816. MidiEventHolder (const MidiMessage& message);
  31817. JUCE_LEAK_DETECTOR (MidiEventHolder);
  31818. };
  31819. /** Clears the sequence. */
  31820. void clear();
  31821. /** Returns the number of events in the sequence. */
  31822. int getNumEvents() const;
  31823. /** Returns a pointer to one of the events. */
  31824. MidiEventHolder* getEventPointer (int index) const;
  31825. /** Returns the time of the note-up that matches the note-on at this index.
  31826. If the event at this index isn't a note-on, it'll just return 0.
  31827. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  31828. */
  31829. double getTimeOfMatchingKeyUp (int index) const;
  31830. /** Returns the index of the note-up that matches the note-on at this index.
  31831. If the event at this index isn't a note-on, it'll just return -1.
  31832. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  31833. */
  31834. int getIndexOfMatchingKeyUp (int index) const;
  31835. /** Returns the index of an event. */
  31836. int getIndexOf (MidiEventHolder* event) const;
  31837. /** Returns the index of the first event on or after the given timestamp.
  31838. If the time is beyond the end of the sequence, this will return the
  31839. number of events.
  31840. */
  31841. int getNextIndexAtTime (double timeStamp) const;
  31842. /** Returns the timestamp of the first event in the sequence.
  31843. @see getEndTime
  31844. */
  31845. double getStartTime() const;
  31846. /** Returns the timestamp of the last event in the sequence.
  31847. @see getStartTime
  31848. */
  31849. double getEndTime() const;
  31850. /** Returns the timestamp of the event at a given index.
  31851. If the index is out-of-range, this will return 0.0
  31852. */
  31853. double getEventTime (int index) const;
  31854. /** Inserts a midi message into the sequence.
  31855. The index at which the new message gets inserted will depend on its timestamp,
  31856. because the sequence is kept sorted.
  31857. Remember to call updateMatchedPairs() after adding note-on events.
  31858. @param newMessage the new message to add (an internal copy will be made)
  31859. @param timeAdjustment an optional value to add to the timestamp of the message
  31860. that will be inserted
  31861. @see updateMatchedPairs
  31862. */
  31863. void addEvent (const MidiMessage& newMessage,
  31864. double timeAdjustment = 0);
  31865. /** Deletes one of the events in the sequence.
  31866. Remember to call updateMatchedPairs() after removing events.
  31867. @param index the index of the event to delete
  31868. @param deleteMatchingNoteUp whether to also remove the matching note-off
  31869. if the event you're removing is a note-on
  31870. */
  31871. void deleteEvent (int index, bool deleteMatchingNoteUp);
  31872. /** Merges another sequence into this one.
  31873. Remember to call updateMatchedPairs() after using this method.
  31874. @param other the sequence to add from
  31875. @param timeAdjustmentDelta an amount to add to the timestamps of the midi events
  31876. as they are read from the other sequence
  31877. @param firstAllowableDestTime events will not be added if their time is earlier
  31878. than this time. (This is after their time has been adjusted
  31879. by the timeAdjustmentDelta)
  31880. @param endOfAllowableDestTimes events will not be added if their time is equal to
  31881. or greater than this time. (This is after their time has
  31882. been adjusted by the timeAdjustmentDelta)
  31883. */
  31884. void addSequence (const MidiMessageSequence& other,
  31885. double timeAdjustmentDelta,
  31886. double firstAllowableDestTime,
  31887. double endOfAllowableDestTimes);
  31888. /** Makes sure all the note-on and note-off pairs are up-to-date.
  31889. Call this after moving messages about or deleting/adding messages, and it
  31890. will scan the list and make sure all the note-offs in the MidiEventHolder
  31891. structures are pointing at the correct ones.
  31892. */
  31893. void updateMatchedPairs();
  31894. /** Copies all the messages for a particular midi channel to another sequence.
  31895. @param channelNumberToExtract the midi channel to look for, in the range 1 to 16
  31896. @param destSequence the sequence that the chosen events should be copied to
  31897. @param alsoIncludeMetaEvents if true, any meta-events (which don't apply to a specific
  31898. channel) will also be copied across.
  31899. @see extractSysExMessages
  31900. */
  31901. void extractMidiChannelMessages (int channelNumberToExtract,
  31902. MidiMessageSequence& destSequence,
  31903. bool alsoIncludeMetaEvents) const;
  31904. /** Copies all midi sys-ex messages to another sequence.
  31905. @param destSequence this is the sequence to which any sys-exes in this sequence
  31906. will be added
  31907. @see extractMidiChannelMessages
  31908. */
  31909. void extractSysExMessages (MidiMessageSequence& destSequence) const;
  31910. /** Removes any messages in this sequence that have a specific midi channel.
  31911. @param channelNumberToRemove the midi channel to look for, in the range 1 to 16
  31912. */
  31913. void deleteMidiChannelMessages (int channelNumberToRemove);
  31914. /** Removes any sys-ex messages from this sequence.
  31915. */
  31916. void deleteSysExMessages();
  31917. /** Adds an offset to the timestamps of all events in the sequence.
  31918. @param deltaTime the amount to add to each timestamp.
  31919. */
  31920. void addTimeToMessages (double deltaTime);
  31921. /** Scans through the sequence to determine the state of any midi controllers at
  31922. a given time.
  31923. This will create a sequence of midi controller changes that can be
  31924. used to set all midi controllers to the state they would be in at the
  31925. specified time within this sequence.
  31926. As well as controllers, it will also recreate the midi program number
  31927. and pitch bend position.
  31928. @param channelNumber the midi channel to look for, in the range 1 to 16. Controllers
  31929. for other channels will be ignored.
  31930. @param time the time at which you want to find out the state - there are
  31931. no explicit units for this time measurement, it's the same units
  31932. as used for the timestamps of the messages
  31933. @param resultMessages an array to which midi controller-change messages will be added. This
  31934. will be the minimum number of controller changes to recreate the
  31935. state at the required time.
  31936. */
  31937. void createControllerUpdatesForTime (int channelNumber, double time,
  31938. OwnedArray<MidiMessage>& resultMessages);
  31939. /** Swaps this sequence with another one. */
  31940. void swapWith (MidiMessageSequence& other) noexcept;
  31941. /** @internal */
  31942. static int compareElements (const MidiMessageSequence::MidiEventHolder* first,
  31943. const MidiMessageSequence::MidiEventHolder* second) noexcept;
  31944. private:
  31945. friend class MidiFile;
  31946. OwnedArray <MidiEventHolder> list;
  31947. void sort();
  31948. JUCE_LEAK_DETECTOR (MidiMessageSequence);
  31949. };
  31950. #endif // __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  31951. /*** End of inlined file: juce_MidiMessageSequence.h ***/
  31952. /**
  31953. Reads/writes standard midi format files.
  31954. To read a midi file, create a MidiFile object and call its readFrom() method. You
  31955. can then get the individual midi tracks from it using the getTrack() method.
  31956. To write a file, create a MidiFile object, add some MidiMessageSequence objects
  31957. to it using the addTrack() method, and then call its writeTo() method to stream
  31958. it out.
  31959. @see MidiMessageSequence
  31960. */
  31961. class JUCE_API MidiFile
  31962. {
  31963. public:
  31964. /** Creates an empty MidiFile object.
  31965. */
  31966. MidiFile();
  31967. /** Destructor. */
  31968. ~MidiFile();
  31969. /** Returns the number of tracks in the file.
  31970. @see getTrack, addTrack
  31971. */
  31972. int getNumTracks() const noexcept;
  31973. /** Returns a pointer to one of the tracks in the file.
  31974. @returns a pointer to the track, or 0 if the index is out-of-range
  31975. @see getNumTracks, addTrack
  31976. */
  31977. const MidiMessageSequence* getTrack (int index) const noexcept;
  31978. /** Adds a midi track to the file.
  31979. This will make its own internal copy of the sequence that is passed-in.
  31980. @see getNumTracks, getTrack
  31981. */
  31982. void addTrack (const MidiMessageSequence& trackSequence);
  31983. /** Removes all midi tracks from the file.
  31984. @see getNumTracks
  31985. */
  31986. void clear();
  31987. /** Returns the raw time format code that will be written to a stream.
  31988. After reading a midi file, this method will return the time-format that
  31989. was read from the file's header. It can be changed using the setTicksPerQuarterNote()
  31990. or setSmpteTimeFormat() methods.
  31991. If the value returned is positive, it indicates the number of midi ticks
  31992. per quarter-note - see setTicksPerQuarterNote().
  31993. It it's negative, the upper byte indicates the frames-per-second (but negative), and
  31994. the lower byte is the number of ticks per frame - see setSmpteTimeFormat().
  31995. */
  31996. short getTimeFormat() const noexcept;
  31997. /** Sets the time format to use when this file is written to a stream.
  31998. If this is called, the file will be written as bars/beats using the
  31999. specified resolution, rather than SMPTE absolute times, as would be
  32000. used if setSmpteTimeFormat() had been called instead.
  32001. @param ticksPerQuarterNote e.g. 96, 960
  32002. @see setSmpteTimeFormat
  32003. */
  32004. void setTicksPerQuarterNote (int ticksPerQuarterNote) noexcept;
  32005. /** Sets the time format to use when this file is written to a stream.
  32006. If this is called, the file will be written using absolute times, rather
  32007. than bars/beats as would be the case if setTicksPerBeat() had been called
  32008. instead.
  32009. @param framesPerSecond must be 24, 25, 29 or 30
  32010. @param subframeResolution the sub-second resolution, e.g. 4 (midi time code),
  32011. 8, 10, 80 (SMPTE bit resolution), or 100. For millisecond
  32012. timing, setSmpteTimeFormat (25, 40)
  32013. @see setTicksPerBeat
  32014. */
  32015. void setSmpteTimeFormat (int framesPerSecond,
  32016. int subframeResolution) noexcept;
  32017. /** Makes a list of all the tempo-change meta-events from all tracks in the midi file.
  32018. Useful for finding the positions of all the tempo changes in a file.
  32019. @param tempoChangeEvents a list to which all the events will be added
  32020. */
  32021. void findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const;
  32022. /** Makes a list of all the time-signature meta-events from all tracks in the midi file.
  32023. Useful for finding the positions of all the tempo changes in a file.
  32024. @param timeSigEvents a list to which all the events will be added
  32025. */
  32026. void findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const;
  32027. /** Returns the latest timestamp in any of the tracks.
  32028. (Useful for finding the length of the file).
  32029. */
  32030. double getLastTimestamp() const;
  32031. /** Reads a midi file format stream.
  32032. After calling this, you can get the tracks that were read from the file by using the
  32033. getNumTracks() and getTrack() methods.
  32034. The timestamps of the midi events in the tracks will represent their positions in
  32035. terms of midi ticks. To convert them to seconds, use the convertTimestampTicksToSeconds()
  32036. method.
  32037. @returns true if the stream was read successfully
  32038. */
  32039. bool readFrom (InputStream& sourceStream);
  32040. /** Writes the midi tracks as a standard midi file.
  32041. @returns true if the operation succeeded.
  32042. */
  32043. bool writeTo (OutputStream& destStream);
  32044. /** Converts the timestamp of all the midi events from midi ticks to seconds.
  32045. This will use the midi time format and tempo/time signature info in the
  32046. tracks to convert all the timestamps to absolute values in seconds.
  32047. */
  32048. void convertTimestampTicksToSeconds();
  32049. private:
  32050. OwnedArray <MidiMessageSequence> tracks;
  32051. short timeFormat;
  32052. void readNextTrack (const uint8* data, int size);
  32053. void writeTrack (OutputStream& mainOut, int trackNum);
  32054. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiFile);
  32055. };
  32056. #endif // __JUCE_MIDIFILE_JUCEHEADER__
  32057. /*** End of inlined file: juce_MidiFile.h ***/
  32058. #endif
  32059. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  32060. #endif
  32061. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  32062. /*** Start of inlined file: juce_MidiKeyboardState.h ***/
  32063. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  32064. #define __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  32065. class MidiKeyboardState;
  32066. /**
  32067. Receives events from a MidiKeyboardState object.
  32068. @see MidiKeyboardState
  32069. */
  32070. class JUCE_API MidiKeyboardStateListener
  32071. {
  32072. public:
  32073. MidiKeyboardStateListener() noexcept {}
  32074. virtual ~MidiKeyboardStateListener() {}
  32075. /** Called when one of the MidiKeyboardState's keys is pressed.
  32076. This will be called synchronously when the state is either processing a
  32077. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  32078. when a note is being played with its MidiKeyboardState::noteOn() method.
  32079. Note that this callback could happen from an audio callback thread, so be
  32080. careful not to block, and avoid any UI activity in the callback.
  32081. */
  32082. virtual void handleNoteOn (MidiKeyboardState* source,
  32083. int midiChannel, int midiNoteNumber, float velocity) = 0;
  32084. /** Called when one of the MidiKeyboardState's keys is released.
  32085. This will be called synchronously when the state is either processing a
  32086. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  32087. when a note is being played with its MidiKeyboardState::noteOff() method.
  32088. Note that this callback could happen from an audio callback thread, so be
  32089. careful not to block, and avoid any UI activity in the callback.
  32090. */
  32091. virtual void handleNoteOff (MidiKeyboardState* source,
  32092. int midiChannel, int midiNoteNumber) = 0;
  32093. };
  32094. /**
  32095. Represents a piano keyboard, keeping track of which keys are currently pressed.
  32096. This object can parse a stream of midi events, using them to update its idea
  32097. of which keys are pressed for each individiual midi channel.
  32098. When keys go up or down, it can broadcast these events to listener objects.
  32099. It also allows key up/down events to be triggered with its noteOn() and noteOff()
  32100. methods, and midi messages for these events will be merged into the
  32101. midi stream that gets processed by processNextMidiBuffer().
  32102. */
  32103. class JUCE_API MidiKeyboardState
  32104. {
  32105. public:
  32106. MidiKeyboardState();
  32107. ~MidiKeyboardState();
  32108. /** Resets the state of the object.
  32109. All internal data for all the channels is reset, but no events are sent as a
  32110. result.
  32111. If you want to release any keys that are currently down, and to send out note-up
  32112. midi messages for this, use the allNotesOff() method instead.
  32113. */
  32114. void reset();
  32115. /** Returns true if the given midi key is currently held down for the given midi channel.
  32116. The channel number must be between 1 and 16. If you want to see if any notes are
  32117. on for a range of channels, use the isNoteOnForChannels() method.
  32118. */
  32119. bool isNoteOn (int midiChannel, int midiNoteNumber) const noexcept;
  32120. /** Returns true if the given midi key is currently held down on any of a set of midi channels.
  32121. The channel mask has a bit set for each midi channel you want to test for - bit
  32122. 0 = midi channel 1, bit 1 = midi channel 2, etc.
  32123. If a note is on for at least one of the specified channels, this returns true.
  32124. */
  32125. bool isNoteOnForChannels (int midiChannelMask, int midiNoteNumber) const noexcept;
  32126. /** Turns a specified note on.
  32127. This will cause a suitable midi note-on event to be injected into the midi buffer during the
  32128. next call to processNextMidiBuffer().
  32129. It will also trigger a synchronous callback to the listeners to tell them that the key has
  32130. gone down.
  32131. */
  32132. void noteOn (int midiChannel, int midiNoteNumber, float velocity);
  32133. /** Turns a specified note off.
  32134. This will cause a suitable midi note-off event to be injected into the midi buffer during the
  32135. next call to processNextMidiBuffer().
  32136. It will also trigger a synchronous callback to the listeners to tell them that the key has
  32137. gone up.
  32138. But if the note isn't acutally down for the given channel, this method will in fact do nothing.
  32139. */
  32140. void noteOff (int midiChannel, int midiNoteNumber);
  32141. /** This will turn off any currently-down notes for the given midi channel.
  32142. If you pass 0 for the midi channel, it will in fact turn off all notes on all channels.
  32143. Calling this method will make calls to noteOff(), so can trigger synchronous callbacks
  32144. and events being added to the midi stream.
  32145. */
  32146. void allNotesOff (int midiChannel);
  32147. /** Looks at a key-up/down event and uses it to update the state of this object.
  32148. To process a buffer full of midi messages, use the processNextMidiBuffer() method
  32149. instead.
  32150. */
  32151. void processNextMidiEvent (const MidiMessage& message);
  32152. /** Scans a midi stream for up/down events and adds its own events to it.
  32153. This will look for any up/down events and use them to update the internal state,
  32154. synchronously making suitable callbacks to the listeners.
  32155. If injectIndirectEvents is true, then midi events to produce the recent noteOn()
  32156. and noteOff() calls will be added into the buffer.
  32157. Only the section of the buffer whose timestamps are between startSample and
  32158. (startSample + numSamples) will be affected, and any events added will be placed
  32159. between these times.
  32160. If you're going to use this method, you'll need to keep calling it regularly for
  32161. it to work satisfactorily.
  32162. To process a single midi event at a time, use the processNextMidiEvent() method
  32163. instead.
  32164. */
  32165. void processNextMidiBuffer (MidiBuffer& buffer,
  32166. int startSample,
  32167. int numSamples,
  32168. bool injectIndirectEvents);
  32169. /** Registers a listener for callbacks when keys go up or down.
  32170. @see removeListener
  32171. */
  32172. void addListener (MidiKeyboardStateListener* listener);
  32173. /** Deregisters a listener.
  32174. @see addListener
  32175. */
  32176. void removeListener (MidiKeyboardStateListener* listener);
  32177. private:
  32178. CriticalSection lock;
  32179. uint16 noteStates [128];
  32180. MidiBuffer eventsToAdd;
  32181. Array <MidiKeyboardStateListener*> listeners;
  32182. void noteOnInternal (int midiChannel, int midiNoteNumber, float velocity);
  32183. void noteOffInternal (int midiChannel, int midiNoteNumber);
  32184. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiKeyboardState);
  32185. };
  32186. #endif // __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  32187. /*** End of inlined file: juce_MidiKeyboardState.h ***/
  32188. #endif
  32189. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  32190. #endif
  32191. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  32192. /*** Start of inlined file: juce_MidiMessageCollector.h ***/
  32193. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  32194. #define __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  32195. /**
  32196. Collects incoming realtime MIDI messages and turns them into blocks suitable for
  32197. processing by a block-based audio callback.
  32198. The class can also be used as either a MidiKeyboardStateListener or a MidiInputCallback
  32199. so it can easily use a midi input or keyboard component as its source.
  32200. @see MidiMessage, MidiInput
  32201. */
  32202. class JUCE_API MidiMessageCollector : public MidiKeyboardStateListener,
  32203. public MidiInputCallback
  32204. {
  32205. public:
  32206. /** Creates a MidiMessageCollector. */
  32207. MidiMessageCollector();
  32208. /** Destructor. */
  32209. ~MidiMessageCollector();
  32210. /** Clears any messages from the queue.
  32211. You need to call this method before starting to use the collector, so that
  32212. it knows the correct sample rate to use.
  32213. */
  32214. void reset (double sampleRate);
  32215. /** Takes an incoming real-time message and adds it to the queue.
  32216. The message's timestamp is taken, and it will be ready for retrieval as part
  32217. of the block returned by the next call to removeNextBlockOfMessages().
  32218. This method is fully thread-safe when overlapping calls are made with
  32219. removeNextBlockOfMessages().
  32220. */
  32221. void addMessageToQueue (const MidiMessage& message);
  32222. /** Removes all the pending messages from the queue as a buffer.
  32223. This will also correct the messages' timestamps to make sure they're in
  32224. the range 0 to numSamples - 1.
  32225. This call should be made regularly by something like an audio processing
  32226. callback, because the time that it happens is used in calculating the
  32227. midi event positions.
  32228. This method is fully thread-safe when overlapping calls are made with
  32229. addMessageToQueue().
  32230. */
  32231. void removeNextBlockOfMessages (MidiBuffer& destBuffer, int numSamples);
  32232. /** @internal */
  32233. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  32234. /** @internal */
  32235. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  32236. /** @internal */
  32237. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  32238. private:
  32239. double lastCallbackTime;
  32240. CriticalSection midiCallbackLock;
  32241. MidiBuffer incomingMessages;
  32242. double sampleRate;
  32243. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiMessageCollector);
  32244. };
  32245. #endif // __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  32246. /*** End of inlined file: juce_MidiMessageCollector.h ***/
  32247. #endif
  32248. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  32249. #endif
  32250. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  32251. #endif
  32252. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  32253. /*** Start of inlined file: juce_AudioUnitPluginFormat.h ***/
  32254. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  32255. #define __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  32256. /*** Start of inlined file: juce_AudioPluginFormat.h ***/
  32257. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  32258. #define __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  32259. /*** Start of inlined file: juce_AudioPluginInstance.h ***/
  32260. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  32261. #define __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  32262. /*** Start of inlined file: juce_AudioProcessor.h ***/
  32263. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  32264. #define __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  32265. /*** Start of inlined file: juce_AudioProcessorEditor.h ***/
  32266. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  32267. #define __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  32268. class AudioProcessor;
  32269. /**
  32270. Base class for the component that acts as the GUI for an AudioProcessor.
  32271. Derive your editor component from this class, and create an instance of it
  32272. by overriding the AudioProcessor::createEditor() method.
  32273. @see AudioProcessor, GenericAudioProcessorEditor
  32274. */
  32275. class JUCE_API AudioProcessorEditor : public Component
  32276. {
  32277. protected:
  32278. /** Creates an editor for the specified processor.
  32279. */
  32280. AudioProcessorEditor (AudioProcessor* owner);
  32281. public:
  32282. /** Destructor. */
  32283. ~AudioProcessorEditor();
  32284. /** Returns a pointer to the processor that this editor represents. */
  32285. AudioProcessor* getAudioProcessor() const noexcept { return owner; }
  32286. private:
  32287. AudioProcessor* const owner;
  32288. JUCE_DECLARE_NON_COPYABLE (AudioProcessorEditor);
  32289. };
  32290. #endif // __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  32291. /*** End of inlined file: juce_AudioProcessorEditor.h ***/
  32292. /*** Start of inlined file: juce_AudioProcessorListener.h ***/
  32293. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  32294. #define __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  32295. class AudioProcessor;
  32296. /**
  32297. Base class for listeners that want to know about changes to an AudioProcessor.
  32298. Use AudioProcessor::addListener() to register your listener with an AudioProcessor.
  32299. @see AudioProcessor
  32300. */
  32301. class JUCE_API AudioProcessorListener
  32302. {
  32303. public:
  32304. /** Destructor. */
  32305. virtual ~AudioProcessorListener() {}
  32306. /** Receives a callback when a parameter is changed.
  32307. IMPORTANT NOTE: this will be called synchronously when a parameter changes, and
  32308. many audio processors will change their parameter during their audio callback.
  32309. This means that not only has your handler code got to be completely thread-safe,
  32310. but it's also got to be VERY fast, and avoid blocking. If you need to handle
  32311. this event on your message thread, use this callback to trigger an AsyncUpdater
  32312. or ChangeBroadcaster which you can respond to on the message thread.
  32313. */
  32314. virtual void audioProcessorParameterChanged (AudioProcessor* processor,
  32315. int parameterIndex,
  32316. float newValue) = 0;
  32317. /** Called to indicate that something else in the plugin has changed, like its
  32318. program, number of parameters, etc.
  32319. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  32320. call it during their audio callback. This means that not only has your handler code
  32321. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  32322. blocking. If you need to handle this event on your message thread, use this callback
  32323. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  32324. message thread.
  32325. */
  32326. virtual void audioProcessorChanged (AudioProcessor* processor) = 0;
  32327. /** Indicates that a parameter change gesture has started.
  32328. E.g. if the user is dragging a slider, this would be called when they first
  32329. press the mouse button, and audioProcessorParameterChangeGestureEnd would be
  32330. called when they release it.
  32331. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  32332. call it during their audio callback. This means that not only has your handler code
  32333. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  32334. blocking. If you need to handle this event on your message thread, use this callback
  32335. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  32336. message thread.
  32337. @see audioProcessorParameterChangeGestureEnd
  32338. */
  32339. virtual void audioProcessorParameterChangeGestureBegin (AudioProcessor* processor,
  32340. int parameterIndex);
  32341. /** Indicates that a parameter change gesture has finished.
  32342. E.g. if the user is dragging a slider, this would be called when they release
  32343. the mouse button.
  32344. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  32345. call it during their audio callback. This means that not only has your handler code
  32346. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  32347. blocking. If you need to handle this event on your message thread, use this callback
  32348. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  32349. message thread.
  32350. @see audioProcessorParameterChangeGestureBegin
  32351. */
  32352. virtual void audioProcessorParameterChangeGestureEnd (AudioProcessor* processor,
  32353. int parameterIndex);
  32354. };
  32355. #endif // __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  32356. /*** End of inlined file: juce_AudioProcessorListener.h ***/
  32357. /*** Start of inlined file: juce_AudioPlayHead.h ***/
  32358. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  32359. #define __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  32360. /**
  32361. A subclass of AudioPlayHead can supply information about the position and
  32362. status of a moving play head during audio playback.
  32363. One of these can be supplied to an AudioProcessor object so that it can find
  32364. out about the position of the audio that it is rendering.
  32365. @see AudioProcessor::setPlayHead, AudioProcessor::getPlayHead
  32366. */
  32367. class JUCE_API AudioPlayHead
  32368. {
  32369. protected:
  32370. AudioPlayHead() {}
  32371. public:
  32372. virtual ~AudioPlayHead() {}
  32373. /** Frame rate types. */
  32374. enum FrameRateType
  32375. {
  32376. fps24 = 0,
  32377. fps25 = 1,
  32378. fps2997 = 2,
  32379. fps30 = 3,
  32380. fps2997drop = 4,
  32381. fps30drop = 5,
  32382. fpsUnknown = 99
  32383. };
  32384. /** This structure is filled-in by the AudioPlayHead::getCurrentPosition() method.
  32385. */
  32386. struct CurrentPositionInfo
  32387. {
  32388. /** The tempo in BPM */
  32389. double bpm;
  32390. /** Time signature numerator, e.g. the 3 of a 3/4 time sig */
  32391. int timeSigNumerator;
  32392. /** Time signature denominator, e.g. the 4 of a 3/4 time sig */
  32393. int timeSigDenominator;
  32394. /** The current play position, in seconds from the start of the edit. */
  32395. double timeInSeconds;
  32396. /** For timecode, the position of the start of the edit, in seconds from 00:00:00:00. */
  32397. double editOriginTime;
  32398. /** The current play position in pulses-per-quarter-note.
  32399. This is the number of quarter notes since the edit start.
  32400. */
  32401. double ppqPosition;
  32402. /** The position of the start of the last bar, in pulses-per-quarter-note.
  32403. This is the number of quarter notes from the start of the edit to the
  32404. start of the current bar.
  32405. Note - this value may be unavailable on some hosts, e.g. Pro-Tools. If
  32406. it's not available, the value will be 0.
  32407. */
  32408. double ppqPositionOfLastBarStart;
  32409. /** The video frame rate, if applicable. */
  32410. FrameRateType frameRate;
  32411. /** True if the transport is currently playing. */
  32412. bool isPlaying;
  32413. /** True if the transport is currently recording.
  32414. (When isRecording is true, then isPlaying will also be true).
  32415. */
  32416. bool isRecording;
  32417. bool operator== (const CurrentPositionInfo& other) const noexcept;
  32418. bool operator!= (const CurrentPositionInfo& other) const noexcept;
  32419. void resetToDefault();
  32420. };
  32421. /** Fills-in the given structure with details about the transport's
  32422. position at the start of the current processing block.
  32423. */
  32424. virtual bool getCurrentPosition (CurrentPositionInfo& result) = 0;
  32425. };
  32426. #endif // __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  32427. /*** End of inlined file: juce_AudioPlayHead.h ***/
  32428. /**
  32429. Base class for audio processing filters or plugins.
  32430. This is intended to act as a base class of audio filter that is general enough to
  32431. be wrapped as a VST, AU, RTAS, etc, or used internally.
  32432. It is also used by the plugin hosting code as the wrapper around an instance
  32433. of a loaded plugin.
  32434. Derive your filter class from this base class, and if you're building a plugin,
  32435. you should implement a global function called createPluginFilter() which creates
  32436. and returns a new instance of your subclass.
  32437. */
  32438. class JUCE_API AudioProcessor
  32439. {
  32440. protected:
  32441. /** Constructor.
  32442. You can also do your initialisation tasks in the initialiseFilterInfo()
  32443. call, which will be made after this object has been created.
  32444. */
  32445. AudioProcessor();
  32446. public:
  32447. /** Destructor. */
  32448. virtual ~AudioProcessor();
  32449. /** Returns the name of this processor.
  32450. */
  32451. virtual const String getName() const = 0;
  32452. /** Called before playback starts, to let the filter prepare itself.
  32453. The sample rate is the target sample rate, and will remain constant until
  32454. playback stops.
  32455. The estimatedSamplesPerBlock value is a HINT about the typical number of
  32456. samples that will be processed for each callback, but isn't any kind
  32457. of guarantee. The actual block sizes that the host uses may be different
  32458. each time the callback happens, and may be more or less than this value.
  32459. */
  32460. virtual void prepareToPlay (double sampleRate,
  32461. int estimatedSamplesPerBlock) = 0;
  32462. /** Called after playback has stopped, to let the filter free up any resources it
  32463. no longer needs.
  32464. */
  32465. virtual void releaseResources() = 0;
  32466. /** Renders the next block.
  32467. When this method is called, the buffer contains a number of channels which is
  32468. at least as great as the maximum number of input and output channels that
  32469. this filter is using. It will be filled with the filter's input data and
  32470. should be replaced with the filter's output.
  32471. So for example if your filter has 2 input channels and 4 output channels, then
  32472. the buffer will contain 4 channels, the first two being filled with the
  32473. input data. Your filter should read these, do its processing, and replace
  32474. the contents of all 4 channels with its output.
  32475. Or if your filter has 5 inputs and 2 outputs, the buffer will have 5 channels,
  32476. all filled with data, and your filter should overwrite the first 2 of these
  32477. with its output. But be VERY careful not to write anything to the last 3
  32478. channels, as these might be mapped to memory that the host assumes is read-only!
  32479. Note that if you have more outputs than inputs, then only those channels that
  32480. correspond to an input channel are guaranteed to contain sensible data - e.g.
  32481. in the case of 2 inputs and 4 outputs, the first two channels contain the input,
  32482. but the last two channels may contain garbage, so you should be careful not to
  32483. let this pass through without being overwritten or cleared.
  32484. Also note that the buffer may have more channels than are strictly necessary,
  32485. but your should only read/write from the ones that your filter is supposed to
  32486. be using.
  32487. The number of samples in these buffers is NOT guaranteed to be the same for every
  32488. callback, and may be more or less than the estimated value given to prepareToPlay().
  32489. Your code must be able to cope with variable-sized blocks, or you're going to get
  32490. clicks and crashes!
  32491. If the filter is receiving a midi input, then the midiMessages array will be filled
  32492. with the midi messages for this block. Each message's timestamp will indicate the
  32493. message's time, as a number of samples from the start of the block.
  32494. Any messages left in the midi buffer when this method has finished are assumed to
  32495. be the filter's midi output. This means that your filter should be careful to
  32496. clear any incoming messages from the array if it doesn't want them to be passed-on.
  32497. Be very careful about what you do in this callback - it's going to be called by
  32498. the audio thread, so any kind of interaction with the UI is absolutely
  32499. out of the question. If you change a parameter in here and need to tell your UI to
  32500. update itself, the best way is probably to inherit from a ChangeBroadcaster, let
  32501. the UI components register as listeners, and then call sendChangeMessage() inside the
  32502. processBlock() method to send out an asynchronous message. You could also use
  32503. the AsyncUpdater class in a similar way.
  32504. */
  32505. virtual void processBlock (AudioSampleBuffer& buffer,
  32506. MidiBuffer& midiMessages) = 0;
  32507. /** Returns the current AudioPlayHead object that should be used to find
  32508. out the state and position of the playhead.
  32509. You can call this from your processBlock() method, and use the AudioPlayHead
  32510. object to get the details about the time of the start of the block currently
  32511. being processed.
  32512. If the host hasn't supplied a playhead object, this will return 0.
  32513. */
  32514. AudioPlayHead* getPlayHead() const noexcept { return playHead; }
  32515. /** Returns the current sample rate.
  32516. This can be called from your processBlock() method - it's not guaranteed
  32517. to be valid at any other time, and may return 0 if it's unknown.
  32518. */
  32519. double getSampleRate() const noexcept { return sampleRate; }
  32520. /** Returns the current typical block size that is being used.
  32521. This can be called from your processBlock() method - it's not guaranteed
  32522. to be valid at any other time.
  32523. Remember it's not the ONLY block size that may be used when calling
  32524. processBlock, it's just the normal one. The actual block sizes used may be
  32525. larger or smaller than this, and will vary between successive calls.
  32526. */
  32527. int getBlockSize() const noexcept { return blockSize; }
  32528. /** Returns the number of input channels that the host will be sending the filter.
  32529. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  32530. number of channels that your filter would prefer to have, and this method lets
  32531. you know how many the host is actually using.
  32532. Note that this method is only valid during or after the prepareToPlay()
  32533. method call. Until that point, the number of channels will be unknown.
  32534. */
  32535. int getNumInputChannels() const noexcept { return numInputChannels; }
  32536. /** Returns the number of output channels that the host will be sending the filter.
  32537. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  32538. number of channels that your filter would prefer to have, and this method lets
  32539. you know how many the host is actually using.
  32540. Note that this method is only valid during or after the prepareToPlay()
  32541. method call. Until that point, the number of channels will be unknown.
  32542. */
  32543. int getNumOutputChannels() const noexcept { return numOutputChannels; }
  32544. /** Returns the name of one of the input channels, as returned by the host.
  32545. The host might not supply very useful names for channels, and this might be
  32546. something like "1", "2", "left", "right", etc.
  32547. */
  32548. virtual const String getInputChannelName (int channelIndex) const = 0;
  32549. /** Returns the name of one of the output channels, as returned by the host.
  32550. The host might not supply very useful names for channels, and this might be
  32551. something like "1", "2", "left", "right", etc.
  32552. */
  32553. virtual const String getOutputChannelName (int channelIndex) const = 0;
  32554. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  32555. virtual bool isInputChannelStereoPair (int index) const = 0;
  32556. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  32557. virtual bool isOutputChannelStereoPair (int index) const = 0;
  32558. /** This returns the number of samples delay that the filter imposes on the audio
  32559. passing through it.
  32560. The host will call this to find the latency - the filter itself should set this value
  32561. by calling setLatencySamples() as soon as it can during its initialisation.
  32562. */
  32563. int getLatencySamples() const noexcept { return latencySamples; }
  32564. /** The filter should call this to set the number of samples delay that it introduces.
  32565. The filter should call this as soon as it can during initialisation, and can call it
  32566. later if the value changes.
  32567. */
  32568. void setLatencySamples (int newLatency);
  32569. /** Returns true if the processor wants midi messages. */
  32570. virtual bool acceptsMidi() const = 0;
  32571. /** Returns true if the processor produces midi messages. */
  32572. virtual bool producesMidi() const = 0;
  32573. /** This returns a critical section that will automatically be locked while the host
  32574. is calling the processBlock() method.
  32575. Use it from your UI or other threads to lock access to variables that are used
  32576. by the process callback, but obviously be careful not to keep it locked for
  32577. too long, because that could cause stuttering playback. If you need to do something
  32578. that'll take a long time and need the processing to stop while it happens, use the
  32579. suspendProcessing() method instead.
  32580. @see suspendProcessing
  32581. */
  32582. const CriticalSection& getCallbackLock() const noexcept { return callbackLock; }
  32583. /** Enables and disables the processing callback.
  32584. If you need to do something time-consuming on a thread and would like to make sure
  32585. the audio processing callback doesn't happen until you've finished, use this
  32586. to disable the callback and re-enable it again afterwards.
  32587. E.g.
  32588. @code
  32589. void loadNewPatch()
  32590. {
  32591. suspendProcessing (true);
  32592. ..do something that takes ages..
  32593. suspendProcessing (false);
  32594. }
  32595. @endcode
  32596. If the host tries to make an audio callback while processing is suspended, the
  32597. filter will return an empty buffer, but won't block the audio thread like it would
  32598. do if you use the getCallbackLock() critical section to synchronise access.
  32599. If you're going to use this, your processBlock() method must call isSuspended() and
  32600. check whether it's suspended or not. If it is, then it should skip doing any real
  32601. processing, either emitting silence or passing the input through unchanged.
  32602. @see getCallbackLock
  32603. */
  32604. void suspendProcessing (bool shouldBeSuspended);
  32605. /** Returns true if processing is currently suspended.
  32606. @see suspendProcessing
  32607. */
  32608. bool isSuspended() const noexcept { return suspended; }
  32609. /** A plugin can override this to be told when it should reset any playing voices.
  32610. The default implementation does nothing, but a host may call this to tell the
  32611. plugin that it should stop any tails or sounds that have been left running.
  32612. */
  32613. virtual void reset();
  32614. /** Returns true if the processor is being run in an offline mode for rendering.
  32615. If the processor is being run live on realtime signals, this returns false.
  32616. If the mode is unknown, this will assume it's realtime and return false.
  32617. This value may be unreliable until the prepareToPlay() method has been called,
  32618. and could change each time prepareToPlay() is called.
  32619. @see setNonRealtime()
  32620. */
  32621. bool isNonRealtime() const noexcept { return nonRealtime; }
  32622. /** Called by the host to tell this processor whether it's being used in a non-realime
  32623. capacity for offline rendering or bouncing.
  32624. Whatever value is passed-in will be
  32625. */
  32626. void setNonRealtime (bool isNonRealtime) noexcept;
  32627. /** Creates the filter's UI.
  32628. This can return 0 if you want a UI-less filter, in which case the host may create
  32629. a generic UI that lets the user twiddle the parameters directly.
  32630. If you do want to pass back a component, the component should be created and set to
  32631. the correct size before returning it. If you implement this method, you must
  32632. also implement the hasEditor() method and make it return true.
  32633. Remember not to do anything silly like allowing your filter to keep a pointer to
  32634. the component that gets created - it could be deleted later without any warning, which
  32635. would make your pointer into a dangler. Use the getActiveEditor() method instead.
  32636. The correct way to handle the connection between an editor component and its
  32637. filter is to use something like a ChangeBroadcaster so that the editor can
  32638. register itself as a listener, and be told when a change occurs. This lets them
  32639. safely unregister themselves when they are deleted.
  32640. Here are a few things to bear in mind when writing an editor:
  32641. - Initially there won't be an editor, until the user opens one, or they might
  32642. not open one at all. Your filter mustn't rely on it being there.
  32643. - An editor object may be deleted and a replacement one created again at any time.
  32644. - It's safe to assume that an editor will be deleted before its filter.
  32645. @see hasEditor
  32646. */
  32647. virtual AudioProcessorEditor* createEditor() = 0;
  32648. /** Your filter must override this and return true if it can create an editor component.
  32649. @see createEditor
  32650. */
  32651. virtual bool hasEditor() const = 0;
  32652. /** Returns the active editor, if there is one.
  32653. Bear in mind this can return 0, even if an editor has previously been
  32654. opened.
  32655. */
  32656. AudioProcessorEditor* getActiveEditor() const noexcept { return activeEditor; }
  32657. /** Returns the active editor, or if there isn't one, it will create one.
  32658. This may call createEditor() internally to create the component.
  32659. */
  32660. AudioProcessorEditor* createEditorIfNeeded();
  32661. /** This must return the correct value immediately after the object has been
  32662. created, and mustn't change the number of parameters later.
  32663. */
  32664. virtual int getNumParameters() = 0;
  32665. /** Returns the name of a particular parameter. */
  32666. virtual const String getParameterName (int parameterIndex) = 0;
  32667. /** Called by the host to find out the value of one of the filter's parameters.
  32668. The host will expect the value returned to be between 0 and 1.0.
  32669. This could be called quite frequently, so try to make your code efficient.
  32670. It's also likely to be called by non-UI threads, so the code in here should
  32671. be thread-aware.
  32672. */
  32673. virtual float getParameter (int parameterIndex) = 0;
  32674. /** Returns the value of a parameter as a text string. */
  32675. virtual const String getParameterText (int parameterIndex) = 0;
  32676. /** The host will call this method to change the value of one of the filter's parameters.
  32677. The host may call this at any time, including during the audio processing
  32678. callback, so the filter has to process this very fast and avoid blocking.
  32679. If you want to set the value of a parameter internally, e.g. from your
  32680. editor component, then don't call this directly - instead, use the
  32681. setParameterNotifyingHost() method, which will also send a message to
  32682. the host telling it about the change. If the message isn't sent, the host
  32683. won't be able to automate your parameters properly.
  32684. The value passed will be between 0 and 1.0.
  32685. */
  32686. virtual void setParameter (int parameterIndex,
  32687. float newValue) = 0;
  32688. /** Your filter can call this when it needs to change one of its parameters.
  32689. This could happen when the editor or some other internal operation changes
  32690. a parameter. This method will call the setParameter() method to change the
  32691. value, and will then send a message to the host telling it about the change.
  32692. Note that to make sure the host correctly handles automation, you should call
  32693. the beginParameterChangeGesture() and endParameterChangeGesture() methods to
  32694. tell the host when the user has started and stopped changing the parameter.
  32695. */
  32696. void setParameterNotifyingHost (int parameterIndex,
  32697. float newValue);
  32698. /** Returns true if the host can automate this parameter.
  32699. By default, this returns true for all parameters.
  32700. */
  32701. virtual bool isParameterAutomatable (int parameterIndex) const;
  32702. /** Should return true if this parameter is a "meta" parameter.
  32703. A meta-parameter is a parameter that changes other params. It is used
  32704. by some hosts (e.g. AudioUnit hosts).
  32705. By default this returns false.
  32706. */
  32707. virtual bool isMetaParameter (int parameterIndex) const;
  32708. /** Sends a signal to the host to tell it that the user is about to start changing this
  32709. parameter.
  32710. This allows the host to know when a parameter is actively being held by the user, and
  32711. it may use this information to help it record automation.
  32712. If you call this, it must be matched by a later call to endParameterChangeGesture().
  32713. */
  32714. void beginParameterChangeGesture (int parameterIndex);
  32715. /** Tells the host that the user has finished changing this parameter.
  32716. This allows the host to know when a parameter is actively being held by the user, and
  32717. it may use this information to help it record automation.
  32718. A call to this method must follow a call to beginParameterChangeGesture().
  32719. */
  32720. void endParameterChangeGesture (int parameterIndex);
  32721. /** The filter can call this when something (apart from a parameter value) has changed.
  32722. It sends a hint to the host that something like the program, number of parameters,
  32723. etc, has changed, and that it should update itself.
  32724. */
  32725. void updateHostDisplay();
  32726. /** Returns the number of preset programs the filter supports.
  32727. The value returned must be valid as soon as this object is created, and
  32728. must not change over its lifetime.
  32729. This value shouldn't be less than 1.
  32730. */
  32731. virtual int getNumPrograms() = 0;
  32732. /** Returns the number of the currently active program.
  32733. */
  32734. virtual int getCurrentProgram() = 0;
  32735. /** Called by the host to change the current program.
  32736. */
  32737. virtual void setCurrentProgram (int index) = 0;
  32738. /** Must return the name of a given program. */
  32739. virtual const String getProgramName (int index) = 0;
  32740. /** Called by the host to rename a program.
  32741. */
  32742. virtual void changeProgramName (int index, const String& newName) = 0;
  32743. /** The host will call this method when it wants to save the filter's internal state.
  32744. This must copy any info about the filter's state into the block of memory provided,
  32745. so that the host can store this and later restore it using setStateInformation().
  32746. Note that there's also a getCurrentProgramStateInformation() method, which only
  32747. stores the current program, not the state of the entire filter.
  32748. See also the helper function copyXmlToBinary() for storing settings as XML.
  32749. @see getCurrentProgramStateInformation
  32750. */
  32751. virtual void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData) = 0;
  32752. /** The host will call this method if it wants to save the state of just the filter's
  32753. current program.
  32754. Unlike getStateInformation, this should only return the current program's state.
  32755. Not all hosts support this, and if you don't implement it, the base class
  32756. method just calls getStateInformation() instead. If you do implement it, be
  32757. sure to also implement getCurrentProgramStateInformation.
  32758. @see getStateInformation, setCurrentProgramStateInformation
  32759. */
  32760. virtual void getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  32761. /** This must restore the filter's state from a block of data previously created
  32762. using getStateInformation().
  32763. Note that there's also a setCurrentProgramStateInformation() method, which tries
  32764. to restore just the current program, not the state of the entire filter.
  32765. See also the helper function getXmlFromBinary() for loading settings as XML.
  32766. @see setCurrentProgramStateInformation
  32767. */
  32768. virtual void setStateInformation (const void* data, int sizeInBytes) = 0;
  32769. /** The host will call this method if it wants to restore the state of just the filter's
  32770. current program.
  32771. Not all hosts support this, and if you don't implement it, the base class
  32772. method just calls setStateInformation() instead. If you do implement it, be
  32773. sure to also implement getCurrentProgramStateInformation.
  32774. @see setStateInformation, getCurrentProgramStateInformation
  32775. */
  32776. virtual void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  32777. /** Adds a listener that will be called when an aspect of this processor changes. */
  32778. void addListener (AudioProcessorListener* newListener);
  32779. /** Removes a previously added listener. */
  32780. void removeListener (AudioProcessorListener* listenerToRemove);
  32781. /** Tells the processor to use this playhead object.
  32782. The processor will not take ownership of the object, so the caller must delete it when
  32783. it is no longer being used.
  32784. */
  32785. void setPlayHead (AudioPlayHead* newPlayHead) noexcept;
  32786. /** Not for public use - this is called before deleting an editor component. */
  32787. void editorBeingDeleted (AudioProcessorEditor* editor) noexcept;
  32788. /** Not for public use - this is called to initialise the processor before playing. */
  32789. void setPlayConfigDetails (int numIns, int numOuts,
  32790. double sampleRate,
  32791. int blockSize) noexcept;
  32792. protected:
  32793. /** Helper function that just converts an xml element into a binary blob.
  32794. Use this in your filter's getStateInformation() method if you want to
  32795. store its state as xml.
  32796. Then use getXmlFromBinary() to reverse this operation and retrieve the XML
  32797. from a binary blob.
  32798. */
  32799. static void copyXmlToBinary (const XmlElement& xml,
  32800. JUCE_NAMESPACE::MemoryBlock& destData);
  32801. /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method.
  32802. This might return 0 if the data's unsuitable or corrupted. Otherwise it will return
  32803. an XmlElement object that the caller must delete when no longer needed.
  32804. */
  32805. static XmlElement* getXmlFromBinary (const void* data, int sizeInBytes);
  32806. /** @internal */
  32807. AudioPlayHead* playHead;
  32808. /** @internal */
  32809. void sendParamChangeMessageToListeners (int parameterIndex, float newValue);
  32810. private:
  32811. Array <AudioProcessorListener*> listeners;
  32812. Component::SafePointer<AudioProcessorEditor> activeEditor;
  32813. double sampleRate;
  32814. int blockSize, numInputChannels, numOutputChannels, latencySamples;
  32815. bool suspended, nonRealtime;
  32816. CriticalSection callbackLock, listenerLock;
  32817. #if JUCE_DEBUG
  32818. BigInteger changingParams;
  32819. #endif
  32820. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessor);
  32821. };
  32822. #endif // __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  32823. /*** End of inlined file: juce_AudioProcessor.h ***/
  32824. /*** Start of inlined file: juce_PluginDescription.h ***/
  32825. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  32826. #define __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  32827. /**
  32828. A small class to represent some facts about a particular type of plugin.
  32829. This class is for storing and managing the details about a plugin without
  32830. actually having to load an instance of it.
  32831. A KnownPluginList contains a list of PluginDescription objects.
  32832. @see KnownPluginList
  32833. */
  32834. class JUCE_API PluginDescription
  32835. {
  32836. public:
  32837. PluginDescription();
  32838. PluginDescription (const PluginDescription& other);
  32839. PluginDescription& operator= (const PluginDescription& other);
  32840. ~PluginDescription();
  32841. /** The name of the plugin. */
  32842. String name;
  32843. /** A more descriptive name for the plugin.
  32844. This may be the same as the 'name' field, but some plugins may provide an
  32845. alternative name.
  32846. */
  32847. String descriptiveName;
  32848. /** The plugin format, e.g. "VST", "AudioUnit", etc.
  32849. */
  32850. String pluginFormatName;
  32851. /** A category, such as "Dynamics", "Reverbs", etc.
  32852. */
  32853. String category;
  32854. /** The manufacturer. */
  32855. String manufacturerName;
  32856. /** The version. This string doesn't have any particular format. */
  32857. String version;
  32858. /** Either the file containing the plugin module, or some other unique way
  32859. of identifying it.
  32860. E.g. for an AU, this would be an ID string that the component manager
  32861. could use to retrieve the plugin. For a VST, it's the file path.
  32862. */
  32863. String fileOrIdentifier;
  32864. /** The last time the plugin file was changed.
  32865. This is handy when scanning for new or changed plugins.
  32866. */
  32867. Time lastFileModTime;
  32868. /** A unique ID for the plugin.
  32869. Note that this might not be unique between formats, e.g. a VST and some
  32870. other format might actually have the same id.
  32871. @see createIdentifierString
  32872. */
  32873. int uid;
  32874. /** True if the plugin identifies itself as a synthesiser. */
  32875. bool isInstrument;
  32876. /** The number of inputs. */
  32877. int numInputChannels;
  32878. /** The number of outputs. */
  32879. int numOutputChannels;
  32880. /** Returns true if the two descriptions refer the the same plugin.
  32881. This isn't quite as simple as them just having the same file (because of
  32882. shell plugins).
  32883. */
  32884. bool isDuplicateOf (const PluginDescription& other) const;
  32885. /** Returns a string that can be saved and used to uniquely identify the
  32886. plugin again.
  32887. This contains less info than the XML encoding, and is independent of the
  32888. plugin's file location, so can be used to store a plugin ID for use
  32889. across different machines.
  32890. */
  32891. String createIdentifierString() const;
  32892. /** Creates an XML object containing these details.
  32893. @see loadFromXml
  32894. */
  32895. XmlElement* createXml() const;
  32896. /** Reloads the info in this structure from an XML record that was previously
  32897. saved with createXML().
  32898. Returns true if the XML was a valid plugin description.
  32899. */
  32900. bool loadFromXml (const XmlElement& xml);
  32901. private:
  32902. JUCE_LEAK_DETECTOR (PluginDescription);
  32903. };
  32904. #endif // __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  32905. /*** End of inlined file: juce_PluginDescription.h ***/
  32906. /**
  32907. Base class for an active instance of a plugin.
  32908. This derives from the AudioProcessor class, and adds some extra functionality
  32909. that helps when wrapping dynamically loaded plugins.
  32910. @see AudioProcessor, AudioPluginFormat
  32911. */
  32912. class JUCE_API AudioPluginInstance : public AudioProcessor
  32913. {
  32914. public:
  32915. /** Destructor.
  32916. Make sure that you delete any UI components that belong to this plugin before
  32917. deleting the plugin.
  32918. */
  32919. virtual ~AudioPluginInstance();
  32920. /** Fills-in the appropriate parts of this plugin description object.
  32921. */
  32922. virtual void fillInPluginDescription (PluginDescription& description) const = 0;
  32923. /** Returns a pointer to some kind of platform-specific data about the plugin.
  32924. E.g. For a VST, this value can be cast to an AEffect*. For an AudioUnit, it can be
  32925. cast to an AudioUnit handle.
  32926. */
  32927. virtual void* getPlatformSpecificData();
  32928. protected:
  32929. AudioPluginInstance();
  32930. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPluginInstance);
  32931. };
  32932. #endif // __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  32933. /*** End of inlined file: juce_AudioPluginInstance.h ***/
  32934. class PluginDescription;
  32935. /**
  32936. The base class for a type of plugin format, such as VST, AudioUnit, LADSPA, etc.
  32937. Use the static getNumFormats() and getFormat() calls to find the types
  32938. of format that are available.
  32939. */
  32940. class JUCE_API AudioPluginFormat
  32941. {
  32942. public:
  32943. /** Destructor. */
  32944. virtual ~AudioPluginFormat();
  32945. /** Returns the format name.
  32946. E.g. "VST", "AudioUnit", etc.
  32947. */
  32948. virtual String getName() const = 0;
  32949. /** This tries to create descriptions for all the plugin types available in
  32950. a binary module file.
  32951. The file will be some kind of DLL or bundle.
  32952. Normally there will only be one type returned, but some plugins
  32953. (e.g. VST shells) can use a single DLL to create a set of different plugin
  32954. subtypes, so in that case, each subtype is returned as a separate object.
  32955. */
  32956. virtual void findAllTypesForFile (OwnedArray <PluginDescription>& results,
  32957. const String& fileOrIdentifier) = 0;
  32958. /** Tries to recreate a type from a previously generated PluginDescription.
  32959. @see PluginDescription::createInstance
  32960. */
  32961. virtual AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc) = 0;
  32962. /** Should do a quick check to see if this file or directory might be a plugin of
  32963. this format.
  32964. This is for searching for potential files, so it shouldn't actually try to
  32965. load the plugin or do anything time-consuming.
  32966. */
  32967. virtual bool fileMightContainThisPluginType (const String& fileOrIdentifier) = 0;
  32968. /** Returns a readable version of the name of the plugin that this identifier refers to.
  32969. */
  32970. virtual String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) = 0;
  32971. /** Checks whether this plugin could possibly be loaded.
  32972. It doesn't actually need to load it, just to check whether the file or component
  32973. still exists.
  32974. */
  32975. virtual bool doesPluginStillExist (const PluginDescription& desc) = 0;
  32976. /** Searches a suggested set of directories for any plugins in this format.
  32977. The path might be ignored, e.g. by AUs, which are found by the OS rather
  32978. than manually.
  32979. */
  32980. virtual StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch,
  32981. bool recursive) = 0;
  32982. /** Returns the typical places to look for this kind of plugin.
  32983. Note that if this returns no paths, it means that the format can't be scanned-for
  32984. (i.e. it's an internal format that doesn't live in files)
  32985. */
  32986. virtual FileSearchPath getDefaultLocationsToSearch() = 0;
  32987. protected:
  32988. AudioPluginFormat() noexcept;
  32989. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPluginFormat);
  32990. };
  32991. #endif // __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  32992. /*** End of inlined file: juce_AudioPluginFormat.h ***/
  32993. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  32994. /**
  32995. Implements a plugin format manager for AudioUnits.
  32996. */
  32997. class JUCE_API AudioUnitPluginFormat : public AudioPluginFormat
  32998. {
  32999. public:
  33000. AudioUnitPluginFormat();
  33001. ~AudioUnitPluginFormat();
  33002. String getName() const { return "AudioUnit"; }
  33003. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  33004. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  33005. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  33006. String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  33007. StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  33008. bool doesPluginStillExist (const PluginDescription& desc);
  33009. FileSearchPath getDefaultLocationsToSearch();
  33010. private:
  33011. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginFormat);
  33012. };
  33013. #endif
  33014. #endif // __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  33015. /*** End of inlined file: juce_AudioUnitPluginFormat.h ***/
  33016. #endif
  33017. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  33018. /*** Start of inlined file: juce_DirectXPluginFormat.h ***/
  33019. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  33020. #define __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  33021. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  33022. // Sorry, this file is just a placeholder at the moment!...
  33023. /**
  33024. Implements a plugin format manager for DirectX plugins.
  33025. */
  33026. class JUCE_API DirectXPluginFormat : public AudioPluginFormat
  33027. {
  33028. public:
  33029. DirectXPluginFormat();
  33030. ~DirectXPluginFormat();
  33031. String getName() const { return "DirectX"; }
  33032. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  33033. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  33034. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  33035. String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  33036. FileSearchPath getDefaultLocationsToSearch();
  33037. private:
  33038. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectXPluginFormat);
  33039. };
  33040. #endif
  33041. #endif // __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  33042. /*** End of inlined file: juce_DirectXPluginFormat.h ***/
  33043. #endif
  33044. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  33045. /*** Start of inlined file: juce_LADSPAPluginFormat.h ***/
  33046. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  33047. #define __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  33048. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  33049. // Sorry, this file is just a placeholder at the moment!...
  33050. /**
  33051. Implements a plugin format manager for DirectX plugins.
  33052. */
  33053. class JUCE_API LADSPAPluginFormat : public AudioPluginFormat
  33054. {
  33055. public:
  33056. LADSPAPluginFormat();
  33057. ~LADSPAPluginFormat();
  33058. String getName() const { return "LADSPA"; }
  33059. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  33060. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  33061. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  33062. String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  33063. FileSearchPath getDefaultLocationsToSearch();
  33064. private:
  33065. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LADSPAPluginFormat);
  33066. };
  33067. #endif
  33068. #endif // __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  33069. /*** End of inlined file: juce_LADSPAPluginFormat.h ***/
  33070. #endif
  33071. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  33072. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  33073. #ifdef __aeffect__
  33074. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  33075. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  33076. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  33077. events to the list.
  33078. This is used by both the VST hosting code and the plugin wrapper.
  33079. */
  33080. class VSTMidiEventList
  33081. {
  33082. public:
  33083. VSTMidiEventList()
  33084. : numEventsUsed (0), numEventsAllocated (0)
  33085. {
  33086. }
  33087. ~VSTMidiEventList()
  33088. {
  33089. freeEvents();
  33090. }
  33091. void clear()
  33092. {
  33093. numEventsUsed = 0;
  33094. if (events != nullptr)
  33095. events->numEvents = 0;
  33096. }
  33097. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  33098. {
  33099. ensureSize (numEventsUsed + 1);
  33100. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  33101. events->numEvents = ++numEventsUsed;
  33102. if (numBytes <= 4)
  33103. {
  33104. if (e->type == kVstSysExType)
  33105. {
  33106. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  33107. e->type = kVstMidiType;
  33108. e->byteSize = sizeof (VstMidiEvent);
  33109. e->noteLength = 0;
  33110. e->noteOffset = 0;
  33111. e->detune = 0;
  33112. e->noteOffVelocity = 0;
  33113. }
  33114. e->deltaFrames = frameOffset;
  33115. memcpy (e->midiData, midiData, numBytes);
  33116. }
  33117. else
  33118. {
  33119. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  33120. if (se->type == kVstSysExType)
  33121. delete[] se->sysexDump;
  33122. se->sysexDump = new char [numBytes];
  33123. memcpy (se->sysexDump, midiData, numBytes);
  33124. se->type = kVstSysExType;
  33125. se->byteSize = sizeof (VstMidiSysexEvent);
  33126. se->deltaFrames = frameOffset;
  33127. se->flags = 0;
  33128. se->dumpBytes = numBytes;
  33129. se->resvd1 = 0;
  33130. se->resvd2 = 0;
  33131. }
  33132. }
  33133. // Handy method to pull the events out of an event buffer supplied by the host
  33134. // or plugin.
  33135. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  33136. {
  33137. for (int i = 0; i < events->numEvents; ++i)
  33138. {
  33139. const VstEvent* const e = events->events[i];
  33140. if (e != nullptr)
  33141. {
  33142. if (e->type == kVstMidiType)
  33143. {
  33144. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  33145. 4, e->deltaFrames);
  33146. }
  33147. else if (e->type == kVstSysExType)
  33148. {
  33149. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  33150. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  33151. e->deltaFrames);
  33152. }
  33153. }
  33154. }
  33155. }
  33156. void ensureSize (int numEventsNeeded)
  33157. {
  33158. if (numEventsNeeded > numEventsAllocated)
  33159. {
  33160. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  33161. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  33162. if (events == nullptr)
  33163. events.calloc (size, 1);
  33164. else
  33165. events.realloc (size, 1);
  33166. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  33167. events->events[i] = allocateVSTEvent();
  33168. numEventsAllocated = numEventsNeeded;
  33169. }
  33170. }
  33171. void freeEvents()
  33172. {
  33173. if (events != nullptr)
  33174. {
  33175. for (int i = numEventsAllocated; --i >= 0;)
  33176. freeVSTEvent (events->events[i]);
  33177. events.free();
  33178. numEventsUsed = 0;
  33179. numEventsAllocated = 0;
  33180. }
  33181. }
  33182. HeapBlock <VstEvents> events;
  33183. private:
  33184. int numEventsUsed, numEventsAllocated;
  33185. static VstEvent* allocateVSTEvent()
  33186. {
  33187. VstEvent* const e = (VstEvent*) ::calloc (1, sizeof (VstMidiEvent) > sizeof (VstMidiSysexEvent) ? sizeof (VstMidiEvent)
  33188. : sizeof (VstMidiSysexEvent));
  33189. e->type = kVstMidiType;
  33190. e->byteSize = sizeof (VstMidiEvent);
  33191. return e;
  33192. }
  33193. static void freeVSTEvent (VstEvent* e)
  33194. {
  33195. if (e->type == kVstSysExType)
  33196. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  33197. ::free (e);
  33198. }
  33199. };
  33200. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  33201. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  33202. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  33203. #endif
  33204. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  33205. /*** Start of inlined file: juce_VSTPluginFormat.h ***/
  33206. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  33207. #define __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  33208. #if JUCE_PLUGINHOST_VST
  33209. /**
  33210. Implements a plugin format manager for VSTs.
  33211. */
  33212. class JUCE_API VSTPluginFormat : public AudioPluginFormat
  33213. {
  33214. public:
  33215. VSTPluginFormat();
  33216. ~VSTPluginFormat();
  33217. String getName() const { return "VST"; }
  33218. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  33219. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  33220. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  33221. String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  33222. StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  33223. bool doesPluginStillExist (const PluginDescription& desc);
  33224. FileSearchPath getDefaultLocationsToSearch();
  33225. private:
  33226. void recursiveFileSearch (StringArray& results, const File& dir, const bool recursive);
  33227. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginFormat);
  33228. };
  33229. #endif
  33230. #endif // __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  33231. /*** End of inlined file: juce_VSTPluginFormat.h ***/
  33232. #endif
  33233. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  33234. #endif
  33235. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  33236. /*** Start of inlined file: juce_AudioPluginFormatManager.h ***/
  33237. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  33238. #define __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  33239. /**
  33240. This maintains a list of known AudioPluginFormats.
  33241. @see AudioPluginFormat
  33242. */
  33243. class JUCE_API AudioPluginFormatManager : public DeletedAtShutdown
  33244. {
  33245. public:
  33246. AudioPluginFormatManager();
  33247. /** Destructor. */
  33248. ~AudioPluginFormatManager();
  33249. juce_DeclareSingleton_SingleThreaded (AudioPluginFormatManager, false);
  33250. /** Adds any formats that it knows about, e.g. VST.
  33251. */
  33252. void addDefaultFormats();
  33253. /** Returns the number of types of format that are available.
  33254. Use getFormat() to get one of them.
  33255. */
  33256. int getNumFormats();
  33257. /** Returns one of the available formats.
  33258. @see getNumFormats
  33259. */
  33260. AudioPluginFormat* getFormat (int index);
  33261. /** Adds a format to the list.
  33262. The object passed in will be owned and deleted by the manager.
  33263. */
  33264. void addFormat (AudioPluginFormat* format);
  33265. /** Tries to load the type for this description, by trying all the formats
  33266. that this manager knows about.
  33267. The caller is responsible for deleting the object that is returned.
  33268. If it can't load the plugin, it returns 0 and leaves a message in the
  33269. errorMessage string.
  33270. */
  33271. AudioPluginInstance* createPluginInstance (const PluginDescription& description,
  33272. String& errorMessage) const;
  33273. /** Checks that the file or component for this plugin actually still exists.
  33274. (This won't try to load the plugin)
  33275. */
  33276. bool doesPluginStillExist (const PluginDescription& description) const;
  33277. private:
  33278. OwnedArray <AudioPluginFormat> formats;
  33279. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPluginFormatManager);
  33280. };
  33281. #endif // __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  33282. /*** End of inlined file: juce_AudioPluginFormatManager.h ***/
  33283. #endif
  33284. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  33285. #endif
  33286. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  33287. /*** Start of inlined file: juce_KnownPluginList.h ***/
  33288. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  33289. #define __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  33290. /*** Start of inlined file: juce_PopupMenu.h ***/
  33291. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  33292. #define __JUCE_POPUPMENU_JUCEHEADER__
  33293. /** Creates and displays a popup-menu.
  33294. To show a popup-menu, you create one of these, add some items to it, then
  33295. call its show() method, which returns the id of the item the user selects.
  33296. E.g. @code
  33297. void MyWidget::mouseDown (const MouseEvent& e)
  33298. {
  33299. PopupMenu m;
  33300. m.addItem (1, "item 1");
  33301. m.addItem (2, "item 2");
  33302. const int result = m.show();
  33303. if (result == 0)
  33304. {
  33305. // user dismissed the menu without picking anything
  33306. }
  33307. else if (result == 1)
  33308. {
  33309. // user picked item 1
  33310. }
  33311. else if (result == 2)
  33312. {
  33313. // user picked item 2
  33314. }
  33315. }
  33316. @endcode
  33317. Submenus are easy too: @code
  33318. void MyWidget::mouseDown (const MouseEvent& e)
  33319. {
  33320. PopupMenu subMenu;
  33321. subMenu.addItem (1, "item 1");
  33322. subMenu.addItem (2, "item 2");
  33323. PopupMenu mainMenu;
  33324. mainMenu.addItem (3, "item 3");
  33325. mainMenu.addSubMenu ("other choices", subMenu);
  33326. const int result = m.show();
  33327. ...etc
  33328. }
  33329. @endcode
  33330. */
  33331. class JUCE_API PopupMenu
  33332. {
  33333. public:
  33334. /** Creates an empty popup menu. */
  33335. PopupMenu();
  33336. /** Creates a copy of another menu. */
  33337. PopupMenu (const PopupMenu& other);
  33338. /** Destructor. */
  33339. ~PopupMenu();
  33340. /** Copies this menu from another one. */
  33341. PopupMenu& operator= (const PopupMenu& other);
  33342. /** Resets the menu, removing all its items. */
  33343. void clear();
  33344. /** Appends a new text item for this menu to show.
  33345. @param itemResultId the number that will be returned from the show() method
  33346. if the user picks this item. The value should never be
  33347. zero, because that's used to indicate that the user didn't
  33348. select anything.
  33349. @param itemText the text to show.
  33350. @param isEnabled if false, the item will be shown 'greyed-out' and can't be picked
  33351. @param isTicked if true, the item will be shown with a tick next to it
  33352. @param iconToUse if this is non-zero, it should be an image that will be
  33353. displayed to the left of the item. This method will take its
  33354. own copy of the image passed-in, so there's no need to keep
  33355. it hanging around.
  33356. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  33357. */
  33358. void addItem (int itemResultId,
  33359. const String& itemText,
  33360. bool isEnabled = true,
  33361. bool isTicked = false,
  33362. const Image& iconToUse = Image::null);
  33363. /** Adds an item that represents one of the commands in a command manager object.
  33364. @param commandManager the manager to use to trigger the command and get information
  33365. about it
  33366. @param commandID the ID of the command
  33367. @param displayName if this is non-empty, then this string will be used instead of
  33368. the command's registered name
  33369. */
  33370. void addCommandItem (ApplicationCommandManager* commandManager,
  33371. int commandID,
  33372. const String& displayName = String::empty);
  33373. /** Appends a text item with a special colour.
  33374. This is the same as addItem(), but specifies a colour to use for the
  33375. text, which will override the default colours that are used by the
  33376. current look-and-feel. See addItem() for a description of the parameters.
  33377. */
  33378. void addColouredItem (int itemResultId,
  33379. const String& itemText,
  33380. const Colour& itemTextColour,
  33381. bool isEnabled = true,
  33382. bool isTicked = false,
  33383. const Image& iconToUse = Image::null);
  33384. /** Appends a custom menu item that can't be used to trigger a result.
  33385. This will add a user-defined component to use as a menu item. Unlike the
  33386. addCustomItem() method that takes a PopupMenu::CustomComponent, this version
  33387. can't trigger a result from it, so doesn't take a menu ID. It also doesn't
  33388. delete the component when it's finished, so it's the caller's responsibility
  33389. to manage the component that is passed-in.
  33390. if triggerMenuItemAutomaticallyWhenClicked is true, the menu itself will handle
  33391. detection of a mouse-click on your component, and use that to trigger the
  33392. menu ID specified in itemResultId. If this is false, the menu item can't
  33393. be triggered, so itemResultId is not used.
  33394. @see CustomComponent
  33395. */
  33396. void addCustomItem (int itemResultId,
  33397. Component* customComponent,
  33398. int idealWidth, int idealHeight,
  33399. bool triggerMenuItemAutomaticallyWhenClicked);
  33400. /** Appends a sub-menu.
  33401. If the menu that's passed in is empty, it will appear as an inactive item.
  33402. */
  33403. void addSubMenu (const String& subMenuName,
  33404. const PopupMenu& subMenu,
  33405. bool isEnabled = true,
  33406. const Image& iconToUse = Image::null,
  33407. bool isTicked = false);
  33408. /** Appends a separator to the menu, to help break it up into sections.
  33409. The menu class is smart enough not to display separators at the top or bottom
  33410. of the menu, and it will replace mutliple adjacent separators with a single
  33411. one, so your code can be quite free and easy about adding these, and it'll
  33412. always look ok.
  33413. */
  33414. void addSeparator();
  33415. /** Adds a non-clickable text item to the menu.
  33416. This is a bold-font items which can be used as a header to separate the items
  33417. into named groups.
  33418. */
  33419. void addSectionHeader (const String& title);
  33420. /** Returns the number of items that the menu currently contains.
  33421. (This doesn't count separators).
  33422. */
  33423. int getNumItems() const noexcept;
  33424. /** Returns true if the menu contains a command item that triggers the given command. */
  33425. bool containsCommandItem (int commandID) const;
  33426. /** Returns true if the menu contains any items that can be used. */
  33427. bool containsAnyActiveItems() const noexcept;
  33428. /** Class used to create a set of options to pass to the show() method.
  33429. You can chain together a series of calls to this class's methods to create
  33430. a set of whatever options you want to specify.
  33431. E.g. @code
  33432. PopupMenu menu;
  33433. ...
  33434. menu.showMenu (PopupMenu::Options().withMaximumWidth (100),
  33435. .withMaximumNumColumns (3)
  33436. .withTargetComponent (myComp));
  33437. @endcode
  33438. */
  33439. class JUCE_API Options
  33440. {
  33441. public:
  33442. Options();
  33443. const Options withTargetComponent (Component* targetComponent) const;
  33444. const Options withTargetScreenArea (const Rectangle<int>& targetArea) const;
  33445. const Options withMinimumWidth (int minWidth) const;
  33446. const Options withMaximumNumColumns (int maxNumColumns) const;
  33447. const Options withStandardItemHeight (int standardHeight) const;
  33448. const Options withItemThatMustBeVisible (int idOfItemToBeVisible) const;
  33449. private:
  33450. friend class PopupMenu;
  33451. Rectangle<int> targetArea;
  33452. Component* targetComponent;
  33453. int visibleItemID, minWidth, maxColumns, standardHeight;
  33454. };
  33455. #if JUCE_MODAL_LOOPS_PERMITTED
  33456. /** Displays the menu and waits for the user to pick something.
  33457. This will display the menu modally, and return the ID of the item that the
  33458. user picks. If they click somewhere off the menu to get rid of it without
  33459. choosing anything, this will return 0.
  33460. The current location of the mouse will be used as the position to show the
  33461. menu - to explicitly set the menu's position, use showAt() instead. Depending
  33462. on where this point is on the screen, the menu will appear above, below or
  33463. to the side of the point.
  33464. @param itemIdThatMustBeVisible if you set this to the ID of one of the menu items,
  33465. then when the menu first appears, it will make sure
  33466. that this item is visible. So if the menu has too many
  33467. items to fit on the screen, it will be scrolled to a
  33468. position where this item is visible.
  33469. @param minimumWidth a minimum width for the menu, in pixels. It may be wider
  33470. than this if some items are too long to fit.
  33471. @param maximumNumColumns if there are too many items to fit on-screen in a single
  33472. vertical column, the menu may be laid out as a series of
  33473. columns - this is the maximum number allowed. To use the
  33474. default value for this (probably about 7), you can pass
  33475. in zero.
  33476. @param standardItemHeight if this is non-zero, it will be used as the standard
  33477. height for menu items (apart from custom items)
  33478. @param callback if this is non-zero, the menu will be launched asynchronously,
  33479. returning immediately, and the callback will receive a
  33480. call when the menu is either dismissed or has an item
  33481. selected. This object will be owned and deleted by the
  33482. system, so make sure that it works safely and that any
  33483. pointers that it uses are safely within scope.
  33484. @see showAt
  33485. */
  33486. int show (int itemIdThatMustBeVisible = 0,
  33487. int minimumWidth = 0,
  33488. int maximumNumColumns = 0,
  33489. int standardItemHeight = 0,
  33490. ModalComponentManager::Callback* callback = nullptr);
  33491. /** Displays the menu at a specific location.
  33492. This is the same as show(), but uses a specific location (in global screen
  33493. co-ordinates) rather than the current mouse position.
  33494. The screenAreaToAttachTo parameter indicates a screen area to which the menu
  33495. will be adjacent. Depending on where this is, the menu will decide which edge to
  33496. attach itself to, in order to fit itself fully on-screen. If you just want to
  33497. trigger a menu at a specific point, you can pass in a rectangle of size (0, 0)
  33498. with the position that you want.
  33499. @see show()
  33500. */
  33501. int showAt (const Rectangle<int>& screenAreaToAttachTo,
  33502. int itemIdThatMustBeVisible = 0,
  33503. int minimumWidth = 0,
  33504. int maximumNumColumns = 0,
  33505. int standardItemHeight = 0,
  33506. ModalComponentManager::Callback* callback = nullptr);
  33507. /** Displays the menu as if it's attached to a component such as a button.
  33508. This is similar to showAt(), but will position it next to the given component, e.g.
  33509. so that the menu's edge is aligned with that of the component. This is intended for
  33510. things like buttons that trigger a pop-up menu.
  33511. */
  33512. int showAt (Component* componentToAttachTo,
  33513. int itemIdThatMustBeVisible = 0,
  33514. int minimumWidth = 0,
  33515. int maximumNumColumns = 0,
  33516. int standardItemHeight = 0,
  33517. ModalComponentManager::Callback* callback = nullptr);
  33518. /** Displays and runs the menu modally, with a set of options.
  33519. */
  33520. int showMenu (const Options& options);
  33521. #endif
  33522. /** Runs the menu asynchronously, with a user-provided callback that will receive the result. */
  33523. void showMenuAsync (const Options& options,
  33524. ModalComponentManager::Callback* callback);
  33525. /** Closes any menus that are currently open.
  33526. This might be useful if you have a situation where your window is being closed
  33527. by some means other than a user action, and you'd like to make sure that menus
  33528. aren't left hanging around.
  33529. */
  33530. static bool JUCE_CALLTYPE dismissAllActiveMenus();
  33531. /** Specifies a look-and-feel for the menu and any sub-menus that it has.
  33532. This can be called before show() if you need a customised menu. Be careful
  33533. not to delete the LookAndFeel object before the menu has been deleted.
  33534. */
  33535. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  33536. /** A set of colour IDs to use to change the colour of various aspects of the menu.
  33537. These constants can be used either via the LookAndFeel::setColour()
  33538. method for the look and feel that is set for this menu with setLookAndFeel()
  33539. @see setLookAndFeel, LookAndFeel::setColour, LookAndFeel::findColour
  33540. */
  33541. enum ColourIds
  33542. {
  33543. backgroundColourId = 0x1000700, /**< The colour to fill the menu's background with. */
  33544. textColourId = 0x1000600, /**< The colour for normal menu item text, (unless the
  33545. colour is specified when the item is added). */
  33546. headerTextColourId = 0x1000601, /**< The colour for section header item text (see the
  33547. addSectionHeader() method). */
  33548. highlightedBackgroundColourId = 0x1000900, /**< The colour to fill the background of the currently
  33549. highlighted menu item. */
  33550. highlightedTextColourId = 0x1000800, /**< The colour to use for the text of the currently
  33551. highlighted item. */
  33552. };
  33553. /**
  33554. Allows you to iterate through the items in a pop-up menu, and examine
  33555. their properties.
  33556. To use this, just create one and repeatedly call its next() method. When this
  33557. returns true, all the member variables of the iterator are filled-out with
  33558. information describing the menu item. When it returns false, the end of the
  33559. list has been reached.
  33560. */
  33561. class JUCE_API MenuItemIterator
  33562. {
  33563. public:
  33564. /** Creates an iterator that will scan through the items in the specified
  33565. menu.
  33566. Be careful not to add any items to a menu while it is being iterated,
  33567. or things could get out of step.
  33568. */
  33569. MenuItemIterator (const PopupMenu& menu);
  33570. /** Destructor. */
  33571. ~MenuItemIterator();
  33572. /** Returns true if there is another item, and sets up all this object's
  33573. member variables to reflect that item's properties.
  33574. */
  33575. bool next();
  33576. String itemName;
  33577. const PopupMenu* subMenu;
  33578. int itemId;
  33579. bool isSeparator;
  33580. bool isTicked;
  33581. bool isEnabled;
  33582. bool isCustomComponent;
  33583. bool isSectionHeader;
  33584. const Colour* customColour;
  33585. Image customImage;
  33586. ApplicationCommandManager* commandManager;
  33587. private:
  33588. const PopupMenu& menu;
  33589. int index;
  33590. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuItemIterator);
  33591. };
  33592. /** A user-defined copmonent that can be used as an item in a popup menu.
  33593. @see PopupMenu::addCustomItem
  33594. */
  33595. class JUCE_API CustomComponent : public Component,
  33596. public SingleThreadedReferenceCountedObject
  33597. {
  33598. public:
  33599. /** Creates a custom item.
  33600. If isTriggeredAutomatically is true, then the menu will automatically detect
  33601. a mouse-click on this component and use that to invoke the menu item. If it's
  33602. false, then it's up to your class to manually trigger the item when it wants to.
  33603. */
  33604. CustomComponent (bool isTriggeredAutomatically = true);
  33605. /** Destructor. */
  33606. ~CustomComponent();
  33607. /** Returns a rectangle with the size that this component would like to have.
  33608. Note that the size which this method returns isn't necessarily the one that
  33609. the menu will give it, as the items will be stretched to have a uniform width.
  33610. */
  33611. virtual void getIdealSize (int& idealWidth, int& idealHeight) = 0;
  33612. /** Dismisses the menu, indicating that this item has been chosen.
  33613. This will cause the menu to exit from its modal state, returning
  33614. this item's id as the result.
  33615. */
  33616. void triggerMenuItem();
  33617. /** Returns true if this item should be highlighted because the mouse is over it.
  33618. You can call this method in your paint() method to find out whether
  33619. to draw a highlight.
  33620. */
  33621. bool isItemHighlighted() const noexcept { return isHighlighted; }
  33622. /** @internal */
  33623. bool isTriggeredAutomatically() const noexcept { return triggeredAutomatically; }
  33624. /** @internal */
  33625. void setHighlighted (bool shouldBeHighlighted);
  33626. private:
  33627. bool isHighlighted, triggeredAutomatically;
  33628. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomComponent);
  33629. };
  33630. /** Appends a custom menu item.
  33631. This will add a user-defined component to use as a menu item. The component
  33632. passed in will be deleted by this menu when it's no longer needed.
  33633. @see CustomComponent
  33634. */
  33635. void addCustomItem (int itemResultId, CustomComponent* customComponent);
  33636. private:
  33637. class Item;
  33638. class ItemComponent;
  33639. class Window;
  33640. friend class MenuItemIterator;
  33641. friend class ItemComponent;
  33642. friend class Window;
  33643. friend class CustomComponent;
  33644. friend class MenuBarComponent;
  33645. friend class OwnedArray <Item>;
  33646. friend class OwnedArray <ItemComponent>;
  33647. friend class ScopedPointer <Window>;
  33648. OwnedArray <Item> items;
  33649. LookAndFeel* lookAndFeel;
  33650. bool separatorPending;
  33651. void addSeparatorIfPending();
  33652. Component* createWindow (const Options&, ApplicationCommandManager**) const;
  33653. int showWithOptionalCallback (const Options&, ModalComponentManager::Callback*, bool);
  33654. JUCE_LEAK_DETECTOR (PopupMenu);
  33655. };
  33656. #endif // __JUCE_POPUPMENU_JUCEHEADER__
  33657. /*** End of inlined file: juce_PopupMenu.h ***/
  33658. /**
  33659. Manages a list of plugin types.
  33660. This can be easily edited, saved and loaded, and used to create instances of
  33661. the plugin types in it.
  33662. @see PluginListComponent
  33663. */
  33664. class JUCE_API KnownPluginList : public ChangeBroadcaster
  33665. {
  33666. public:
  33667. /** Creates an empty list.
  33668. */
  33669. KnownPluginList();
  33670. /** Destructor. */
  33671. ~KnownPluginList();
  33672. /** Clears the list. */
  33673. void clear();
  33674. /** Returns the number of types currently in the list.
  33675. @see getType
  33676. */
  33677. int getNumTypes() const noexcept { return types.size(); }
  33678. /** Returns one of the types.
  33679. @see getNumTypes
  33680. */
  33681. PluginDescription* getType (int index) const noexcept { return types [index]; }
  33682. /** Looks for a type in the list which comes from this file.
  33683. */
  33684. PluginDescription* getTypeForFile (const String& fileOrIdentifier) const;
  33685. /** Looks for a type in the list which matches a plugin type ID.
  33686. The identifierString parameter must have been created by
  33687. PluginDescription::createIdentifierString().
  33688. */
  33689. PluginDescription* getTypeForIdentifierString (const String& identifierString) const;
  33690. /** Adds a type manually from its description. */
  33691. bool addType (const PluginDescription& type);
  33692. /** Removes a type. */
  33693. void removeType (int index);
  33694. /** Looks for all types that can be loaded from a given file, and adds them
  33695. to the list.
  33696. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  33697. re-tested if it's not already in the list, or if the file's modification
  33698. time has changed since the list was created. If dontRescanIfAlreadyInList is
  33699. false, the file will always be reloaded and tested.
  33700. Returns true if any new types were added, and all the types found in this
  33701. file (even if it was already known and hasn't been re-scanned) get returned
  33702. in the array.
  33703. */
  33704. bool scanAndAddFile (const String& possiblePluginFileOrIdentifier,
  33705. bool dontRescanIfAlreadyInList,
  33706. OwnedArray <PluginDescription>& typesFound,
  33707. AudioPluginFormat& formatToUse);
  33708. /** Returns true if the specified file is already known about and if it
  33709. hasn't been modified since our entry was created.
  33710. */
  33711. bool isListingUpToDate (const String& possiblePluginFileOrIdentifier) const;
  33712. /** Scans and adds a bunch of files that might have been dragged-and-dropped.
  33713. If any types are found in the files, their descriptions are returned in the array.
  33714. */
  33715. void scanAndAddDragAndDroppedFiles (const StringArray& filenames,
  33716. OwnedArray <PluginDescription>& typesFound);
  33717. /** Sort methods used to change the order of the plugins in the list.
  33718. */
  33719. enum SortMethod
  33720. {
  33721. defaultOrder = 0,
  33722. sortAlphabetically,
  33723. sortByCategory,
  33724. sortByManufacturer,
  33725. sortByFileSystemLocation
  33726. };
  33727. /** Adds all the plugin types to a popup menu so that the user can select one.
  33728. Depending on the sort method, it may add sub-menus for categories,
  33729. manufacturers, etc.
  33730. Use getIndexChosenByMenu() to find out the type that was chosen.
  33731. */
  33732. void addToMenu (PopupMenu& menu,
  33733. const SortMethod sortMethod) const;
  33734. /** Converts a menu item index that has been chosen into its index in this list.
  33735. Returns -1 if it's not an ID that was used.
  33736. @see addToMenu
  33737. */
  33738. int getIndexChosenByMenu (int menuResultCode) const;
  33739. /** Sorts the list. */
  33740. void sort (const SortMethod method);
  33741. /** Creates some XML that can be used to store the state of this list.
  33742. */
  33743. XmlElement* createXml() const;
  33744. /** Recreates the state of this list from its stored XML format.
  33745. */
  33746. void recreateFromXml (const XmlElement& xml);
  33747. private:
  33748. OwnedArray <PluginDescription> types;
  33749. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (KnownPluginList);
  33750. };
  33751. #endif // __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  33752. /*** End of inlined file: juce_KnownPluginList.h ***/
  33753. #endif
  33754. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  33755. #endif
  33756. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  33757. /*** Start of inlined file: juce_PluginDirectoryScanner.h ***/
  33758. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  33759. #define __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  33760. /**
  33761. Scans a directory for plugins, and adds them to a KnownPluginList.
  33762. To use one of these, create it and call scanNextFile() repeatedly, until
  33763. it returns false.
  33764. */
  33765. class JUCE_API PluginDirectoryScanner
  33766. {
  33767. public:
  33768. /**
  33769. Creates a scanner.
  33770. @param listToAddResultsTo this will get the new types added to it.
  33771. @param formatToLookFor this is the type of format that you want to look for
  33772. @param directoriesToSearch the path to search
  33773. @param searchRecursively true to search recursively
  33774. @param deadMansPedalFile if this isn't File::nonexistent, then it will
  33775. be used as a file to store the names of any plugins
  33776. that crash during initialisation. If there are
  33777. any plugins listed in it, then these will always
  33778. be scanned after all other possible files have
  33779. been tried - in this way, even if there's a few
  33780. dodgy plugins in your path, then a couple of rescans
  33781. will still manage to find all the proper plugins.
  33782. It's probably best to choose a file in the user's
  33783. application data directory (alongside your app's
  33784. settings file) for this. The file format it uses
  33785. is just a list of filenames of the modules that
  33786. failed.
  33787. */
  33788. PluginDirectoryScanner (KnownPluginList& listToAddResultsTo,
  33789. AudioPluginFormat& formatToLookFor,
  33790. FileSearchPath directoriesToSearch,
  33791. bool searchRecursively,
  33792. const File& deadMansPedalFile);
  33793. /** Destructor. */
  33794. ~PluginDirectoryScanner();
  33795. /** Tries the next likely-looking file.
  33796. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  33797. re-tested if it's not already in the list, or if the file's modification
  33798. time has changed since the list was created. If dontRescanIfAlreadyInList is
  33799. false, the file will always be reloaded and tested.
  33800. Returns false when there are no more files to try.
  33801. */
  33802. bool scanNextFile (bool dontRescanIfAlreadyInList);
  33803. /** Skips over the next file without scanning it.
  33804. Returns false when there are no more files to try.
  33805. */
  33806. bool skipNextFile();
  33807. /** Returns the description of the plugin that will be scanned during the next
  33808. call to scanNextFile().
  33809. This is handy if you want to show the user which file is currently getting
  33810. scanned.
  33811. */
  33812. const String getNextPluginFileThatWillBeScanned() const;
  33813. /** Returns the estimated progress, between 0 and 1.
  33814. */
  33815. float getProgress() const { return progress; }
  33816. /** This returns a list of all the filenames of things that looked like being
  33817. a plugin file, but which failed to open for some reason.
  33818. */
  33819. const StringArray& getFailedFiles() const noexcept { return failedFiles; }
  33820. private:
  33821. KnownPluginList& list;
  33822. AudioPluginFormat& format;
  33823. StringArray filesOrIdentifiersToScan;
  33824. File deadMansPedalFile;
  33825. StringArray failedFiles;
  33826. int nextIndex;
  33827. float progress;
  33828. StringArray getDeadMansPedalFile();
  33829. void setDeadMansPedalFile (const StringArray& newContents);
  33830. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PluginDirectoryScanner);
  33831. };
  33832. #endif // __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  33833. /*** End of inlined file: juce_PluginDirectoryScanner.h ***/
  33834. #endif
  33835. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  33836. /*** Start of inlined file: juce_PluginListComponent.h ***/
  33837. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  33838. #define __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  33839. /*** Start of inlined file: juce_ListBox.h ***/
  33840. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  33841. #define __JUCE_LISTBOX_JUCEHEADER__
  33842. /*** Start of inlined file: juce_Viewport.h ***/
  33843. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  33844. #define __JUCE_VIEWPORT_JUCEHEADER__
  33845. /*** Start of inlined file: juce_ScrollBar.h ***/
  33846. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  33847. #define __JUCE_SCROLLBAR_JUCEHEADER__
  33848. /*** Start of inlined file: juce_Button.h ***/
  33849. #ifndef __JUCE_BUTTON_JUCEHEADER__
  33850. #define __JUCE_BUTTON_JUCEHEADER__
  33851. /*** Start of inlined file: juce_TooltipWindow.h ***/
  33852. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  33853. #define __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  33854. /*** Start of inlined file: juce_TooltipClient.h ***/
  33855. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  33856. #define __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  33857. /**
  33858. Components that want to use pop-up tooltips should implement this interface.
  33859. A TooltipWindow will wait for the mouse to hover over a component that
  33860. implements the TooltipClient interface, and when it finds one, it will display
  33861. the tooltip returned by its getTooltip() method.
  33862. @see TooltipWindow, SettableTooltipClient
  33863. */
  33864. class JUCE_API TooltipClient
  33865. {
  33866. public:
  33867. /** Destructor. */
  33868. virtual ~TooltipClient() {}
  33869. /** Returns the string that this object wants to show as its tooltip. */
  33870. virtual const String getTooltip() = 0;
  33871. };
  33872. /**
  33873. An implementation of TooltipClient that stores the tooltip string and a method
  33874. for changing it.
  33875. This makes it easy to add a tooltip to a custom component, by simply adding this
  33876. as a base class and calling setTooltip().
  33877. Many of the Juce widgets already use this as a base class to implement their
  33878. tooltips.
  33879. @see TooltipClient, TooltipWindow
  33880. */
  33881. class JUCE_API SettableTooltipClient : public TooltipClient
  33882. {
  33883. public:
  33884. /** Destructor. */
  33885. virtual ~SettableTooltipClient() {}
  33886. /** Assigns a new tooltip to this object. */
  33887. virtual void setTooltip (const String& newTooltip) { tooltipString = newTooltip; }
  33888. /** Returns the tooltip assigned to this object. */
  33889. virtual const String getTooltip() { return tooltipString; }
  33890. protected:
  33891. SettableTooltipClient() {}
  33892. private:
  33893. String tooltipString;
  33894. };
  33895. #endif // __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  33896. /*** End of inlined file: juce_TooltipClient.h ***/
  33897. /**
  33898. A window that displays a pop-up tooltip when the mouse hovers over another component.
  33899. To enable tooltips in your app, just create a single instance of a TooltipWindow
  33900. object.
  33901. The TooltipWindow object will then stay invisible, waiting until the mouse
  33902. hovers for the specified length of time - it will then see if it's currently
  33903. over a component which implements the TooltipClient interface, and if so,
  33904. it will make itself visible to show the tooltip in the appropriate place.
  33905. @see TooltipClient, SettableTooltipClient
  33906. */
  33907. class JUCE_API TooltipWindow : public Component,
  33908. private Timer
  33909. {
  33910. public:
  33911. /** Creates a tooltip window.
  33912. Make sure your app only creates one instance of this class, otherwise you'll
  33913. get multiple overlaid tooltips appearing. The window will initially be invisible
  33914. and will make itself visible when it needs to display a tip.
  33915. To change the style of tooltips, see the LookAndFeel class for its tooltip
  33916. methods.
  33917. @param parentComponent if set to 0, the TooltipWindow will appear on the desktop,
  33918. otherwise the tooltip will be added to the given parent
  33919. component.
  33920. @param millisecondsBeforeTipAppears the time for which the mouse has to stay still
  33921. before a tooltip will be shown
  33922. @see TooltipClient, LookAndFeel::drawTooltip, LookAndFeel::getTooltipSize
  33923. */
  33924. explicit TooltipWindow (Component* parentComponent = nullptr,
  33925. int millisecondsBeforeTipAppears = 700);
  33926. /** Destructor. */
  33927. ~TooltipWindow();
  33928. /** Changes the time before the tip appears.
  33929. This lets you change the value that was set in the constructor.
  33930. */
  33931. void setMillisecondsBeforeTipAppears (int newTimeMs = 700) noexcept;
  33932. /** A set of colour IDs to use to change the colour of various aspects of the tooltip.
  33933. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33934. methods.
  33935. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33936. */
  33937. enum ColourIds
  33938. {
  33939. backgroundColourId = 0x1001b00, /**< The colour to fill the background with. */
  33940. textColourId = 0x1001c00, /**< The colour to use for the text. */
  33941. outlineColourId = 0x1001c10 /**< The colour to use to draw an outline around the tooltip. */
  33942. };
  33943. private:
  33944. int millisecondsBeforeTipAppears;
  33945. Point<int> lastMousePos;
  33946. int mouseClicks;
  33947. unsigned int lastCompChangeTime, lastHideTime;
  33948. Component* lastComponentUnderMouse;
  33949. bool changedCompsSinceShown;
  33950. String tipShowing, lastTipUnderMouse;
  33951. void paint (Graphics& g);
  33952. void mouseEnter (const MouseEvent& e);
  33953. void timerCallback();
  33954. static String getTipFor (Component* c);
  33955. void showFor (const String& tip);
  33956. void hide();
  33957. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TooltipWindow);
  33958. };
  33959. #endif // __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  33960. /*** End of inlined file: juce_TooltipWindow.h ***/
  33961. #if JUCE_VC6
  33962. #define Listener ButtonListener
  33963. #endif
  33964. /**
  33965. A base class for buttons.
  33966. This contains all the logic for button behaviours such as enabling/disabling,
  33967. responding to shortcut keystrokes, auto-repeating when held down, toggle-buttons
  33968. and radio groups, etc.
  33969. @see TextButton, DrawableButton, ToggleButton
  33970. */
  33971. class JUCE_API Button : public Component,
  33972. public SettableTooltipClient,
  33973. public ApplicationCommandManagerListener,
  33974. public ValueListener,
  33975. private KeyListener
  33976. {
  33977. protected:
  33978. /** Creates a button.
  33979. @param buttonName the text to put in the button (the component's name is also
  33980. initially set to this string, but these can be changed later
  33981. using the setName() and setButtonText() methods)
  33982. */
  33983. explicit Button (const String& buttonName);
  33984. public:
  33985. /** Destructor. */
  33986. virtual ~Button();
  33987. /** Changes the button's text.
  33988. @see getButtonText
  33989. */
  33990. void setButtonText (const String& newText);
  33991. /** Returns the text displayed in the button.
  33992. @see setButtonText
  33993. */
  33994. const String& getButtonText() const { return text; }
  33995. /** Returns true if the button is currently being held down by the mouse.
  33996. @see isOver
  33997. */
  33998. bool isDown() const noexcept;
  33999. /** Returns true if the mouse is currently over the button.
  34000. This will be also be true if the mouse is being held down.
  34001. @see isDown
  34002. */
  34003. bool isOver() const noexcept;
  34004. /** A button has an on/off state associated with it, and this changes that.
  34005. By default buttons are 'off' and for simple buttons that you click to perform
  34006. an action you won't change this. Toggle buttons, however will want to
  34007. change their state when turned on or off.
  34008. @param shouldBeOn whether to set the button's toggle state to be on or
  34009. off. If it's a member of a button group, this will
  34010. always try to turn it on, and to turn off any other
  34011. buttons in the group
  34012. @param sendChangeNotification if true, a callback will be made to clicked(); if false
  34013. the button will be repainted but no notification will
  34014. be sent
  34015. @see getToggleState, setRadioGroupId
  34016. */
  34017. void setToggleState (bool shouldBeOn,
  34018. bool sendChangeNotification);
  34019. /** Returns true if the button in 'on'.
  34020. By default buttons are 'off' and for simple buttons that you click to perform
  34021. an action you won't change this. Toggle buttons, however will want to
  34022. change their state when turned on or off.
  34023. @see setToggleState
  34024. */
  34025. bool getToggleState() const noexcept { return isOn.getValue(); }
  34026. /** Returns the Value object that represents the botton's toggle state.
  34027. You can use this Value object to connect the button's state to external values or setters,
  34028. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  34029. your own Value object.
  34030. @see getToggleState, Value
  34031. */
  34032. Value& getToggleStateValue() { return isOn; }
  34033. /** This tells the button to automatically flip the toggle state when
  34034. the button is clicked.
  34035. If set to true, then before the clicked() callback occurs, the toggle-state
  34036. of the button is flipped.
  34037. */
  34038. void setClickingTogglesState (bool shouldToggle) noexcept;
  34039. /** Returns true if this button is set to be an automatic toggle-button.
  34040. This returns the last value that was passed to setClickingTogglesState().
  34041. */
  34042. bool getClickingTogglesState() const noexcept;
  34043. /** Enables the button to act as a member of a mutually-exclusive group
  34044. of 'radio buttons'.
  34045. If the group ID is set to a non-zero number, then this button will
  34046. act as part of a group of buttons with the same ID, only one of
  34047. which can be 'on' at the same time. Note that when it's part of
  34048. a group, clicking a toggle-button that's 'on' won't turn it off.
  34049. To find other buttons with the same ID, this button will search through
  34050. its sibling components for ToggleButtons, so all the buttons for a
  34051. particular group must be placed inside the same parent component.
  34052. Set the group ID back to zero if you want it to act as a normal toggle
  34053. button again.
  34054. @see getRadioGroupId
  34055. */
  34056. void setRadioGroupId (int newGroupId);
  34057. /** Returns the ID of the group to which this button belongs.
  34058. (See setRadioGroupId() for an explanation of this).
  34059. */
  34060. int getRadioGroupId() const noexcept { return radioGroupId; }
  34061. /**
  34062. Used to receive callbacks when a button is clicked.
  34063. @see Button::addListener, Button::removeListener
  34064. */
  34065. class JUCE_API Listener
  34066. {
  34067. public:
  34068. /** Destructor. */
  34069. virtual ~Listener() {}
  34070. /** Called when the button is clicked. */
  34071. virtual void buttonClicked (Button* button) = 0;
  34072. /** Called when the button's state changes. */
  34073. virtual void buttonStateChanged (Button*) {}
  34074. };
  34075. /** Registers a listener to receive events when this button's state changes.
  34076. If the listener is already registered, this will not register it again.
  34077. @see removeListener
  34078. */
  34079. void addListener (Listener* newListener);
  34080. /** Removes a previously-registered button listener
  34081. @see addListener
  34082. */
  34083. void removeListener (Listener* listener);
  34084. /** Causes the button to act as if it's been clicked.
  34085. This will asynchronously make the button draw itself going down and up, and
  34086. will then call back the clicked() method as if mouse was clicked on it.
  34087. @see clicked
  34088. */
  34089. virtual void triggerClick();
  34090. /** Sets a command ID for this button to automatically invoke when it's clicked.
  34091. When the button is pressed, it will use the given manager to trigger the
  34092. command ID.
  34093. Obviously be careful that the ApplicationCommandManager doesn't get deleted
  34094. before this button is. To disable the command triggering, call this method and
  34095. pass 0 for the parameters.
  34096. If generateTooltip is true, then the button's tooltip will be automatically
  34097. generated based on the name of this command and its current shortcut key.
  34098. @see addShortcut, getCommandID
  34099. */
  34100. void setCommandToTrigger (ApplicationCommandManager* commandManagerToUse,
  34101. int commandID,
  34102. bool generateTooltip);
  34103. /** Returns the command ID that was set by setCommandToTrigger().
  34104. */
  34105. int getCommandID() const noexcept { return commandID; }
  34106. /** Assigns a shortcut key to trigger the button.
  34107. The button registers itself with its top-level parent component for keypresses.
  34108. Note that a different way of linking buttons to keypresses is by using the
  34109. setCommandToTrigger() method to invoke a command.
  34110. @see clearShortcuts
  34111. */
  34112. void addShortcut (const KeyPress& key);
  34113. /** Removes all key shortcuts that had been set for this button.
  34114. @see addShortcut
  34115. */
  34116. void clearShortcuts();
  34117. /** Returns true if the given keypress is a shortcut for this button.
  34118. @see addShortcut
  34119. */
  34120. bool isRegisteredForShortcut (const KeyPress& key) const;
  34121. /** Sets an auto-repeat speed for the button when it is held down.
  34122. (Auto-repeat is disabled by default).
  34123. @param initialDelayInMillisecs how long to wait after the mouse is pressed before
  34124. triggering the next click. If this is zero, auto-repeat
  34125. is disabled
  34126. @param repeatDelayInMillisecs the frequently subsequent repeated clicks should be
  34127. triggered
  34128. @param minimumDelayInMillisecs if this is greater than 0, the auto-repeat speed will
  34129. get faster, the longer the button is held down, up to the
  34130. minimum interval specified here
  34131. */
  34132. void setRepeatSpeed (int initialDelayInMillisecs,
  34133. int repeatDelayInMillisecs,
  34134. int minimumDelayInMillisecs = -1) noexcept;
  34135. /** Sets whether the button click should happen when the mouse is pressed or released.
  34136. By default the button is only considered to have been clicked when the mouse is
  34137. released, but setting this to true will make it call the clicked() method as soon
  34138. as the button is pressed.
  34139. This is useful if the button is being used to show a pop-up menu, as it allows
  34140. the click to be used as a drag onto the menu.
  34141. */
  34142. void setTriggeredOnMouseDown (bool isTriggeredOnMouseDown) noexcept;
  34143. /** Returns the number of milliseconds since the last time the button
  34144. went into the 'down' state.
  34145. */
  34146. uint32 getMillisecondsSinceButtonDown() const noexcept;
  34147. /** Sets the tooltip for this button.
  34148. @see TooltipClient, TooltipWindow
  34149. */
  34150. void setTooltip (const String& newTooltip);
  34151. // (implementation of the TooltipClient method)
  34152. const String getTooltip();
  34153. /** A combination of these flags are used by setConnectedEdges().
  34154. */
  34155. enum ConnectedEdgeFlags
  34156. {
  34157. ConnectedOnLeft = 1,
  34158. ConnectedOnRight = 2,
  34159. ConnectedOnTop = 4,
  34160. ConnectedOnBottom = 8
  34161. };
  34162. /** Hints about which edges of the button might be connected to adjoining buttons.
  34163. The value passed in is a bitwise combination of any of the values in the
  34164. ConnectedEdgeFlags enum.
  34165. E.g. if you are placing two buttons adjacent to each other, you could use this to
  34166. indicate which edges are touching, and the LookAndFeel might choose to drawn them
  34167. without rounded corners on the edges that connect. It's only a hint, so the
  34168. LookAndFeel can choose to ignore it if it's not relevent for this type of
  34169. button.
  34170. */
  34171. void setConnectedEdges (int connectedEdgeFlags);
  34172. /** Returns the set of flags passed into setConnectedEdges(). */
  34173. int getConnectedEdgeFlags() const noexcept { return connectedEdgeFlags; }
  34174. /** Indicates whether the button adjoins another one on its left edge.
  34175. @see setConnectedEdges
  34176. */
  34177. bool isConnectedOnLeft() const noexcept { return (connectedEdgeFlags & ConnectedOnLeft) != 0; }
  34178. /** Indicates whether the button adjoins another one on its right edge.
  34179. @see setConnectedEdges
  34180. */
  34181. bool isConnectedOnRight() const noexcept { return (connectedEdgeFlags & ConnectedOnRight) != 0; }
  34182. /** Indicates whether the button adjoins another one on its top edge.
  34183. @see setConnectedEdges
  34184. */
  34185. bool isConnectedOnTop() const noexcept { return (connectedEdgeFlags & ConnectedOnTop) != 0; }
  34186. /** Indicates whether the button adjoins another one on its bottom edge.
  34187. @see setConnectedEdges
  34188. */
  34189. bool isConnectedOnBottom() const noexcept { return (connectedEdgeFlags & ConnectedOnBottom) != 0; }
  34190. /** Used by setState(). */
  34191. enum ButtonState
  34192. {
  34193. buttonNormal,
  34194. buttonOver,
  34195. buttonDown
  34196. };
  34197. /** Can be used to force the button into a particular state.
  34198. This only changes the button's appearance, it won't trigger a click, or stop any mouse-clicks
  34199. from happening.
  34200. The state that you set here will only last until it is automatically changed when the mouse
  34201. enters or exits the button, or the mouse-button is pressed or released.
  34202. */
  34203. void setState (const ButtonState newState);
  34204. // These are deprecated - please use addListener() and removeListener() instead!
  34205. JUCE_DEPRECATED (void addButtonListener (Listener*));
  34206. JUCE_DEPRECATED (void removeButtonListener (Listener*));
  34207. protected:
  34208. /** This method is called when the button has been clicked.
  34209. Subclasses can override this to perform whatever they actions they need
  34210. to do.
  34211. Alternatively, a ButtonListener can be added to the button, and these listeners
  34212. will be called when the click occurs.
  34213. @see triggerClick
  34214. */
  34215. virtual void clicked();
  34216. /** This method is called when the button has been clicked.
  34217. By default it just calls clicked(), but you might want to override it to handle
  34218. things like clicking when a modifier key is pressed, etc.
  34219. @see ModifierKeys
  34220. */
  34221. virtual void clicked (const ModifierKeys& modifiers);
  34222. /** Subclasses should override this to actually paint the button's contents.
  34223. It's better to use this than the paint method, because it gives you information
  34224. about the over/down state of the button.
  34225. @param g the graphics context to use
  34226. @param isMouseOverButton true if the button is either in the 'over' or
  34227. 'down' state
  34228. @param isButtonDown true if the button should be drawn in the 'down' position
  34229. */
  34230. virtual void paintButton (Graphics& g,
  34231. bool isMouseOverButton,
  34232. bool isButtonDown) = 0;
  34233. /** Called when the button's up/down/over state changes.
  34234. Subclasses can override this if they need to do something special when the button
  34235. goes up or down.
  34236. @see isDown, isOver
  34237. */
  34238. virtual void buttonStateChanged();
  34239. /** @internal */
  34240. virtual void internalClickCallback (const ModifierKeys& modifiers);
  34241. /** @internal */
  34242. void handleCommandMessage (int commandId);
  34243. /** @internal */
  34244. void mouseEnter (const MouseEvent& e);
  34245. /** @internal */
  34246. void mouseExit (const MouseEvent& e);
  34247. /** @internal */
  34248. void mouseDown (const MouseEvent& e);
  34249. /** @internal */
  34250. void mouseDrag (const MouseEvent& e);
  34251. /** @internal */
  34252. void mouseUp (const MouseEvent& e);
  34253. /** @internal */
  34254. bool keyPressed (const KeyPress& key);
  34255. /** @internal */
  34256. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  34257. /** @internal */
  34258. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  34259. /** @internal */
  34260. void paint (Graphics& g);
  34261. /** @internal */
  34262. void parentHierarchyChanged();
  34263. /** @internal */
  34264. void visibilityChanged();
  34265. /** @internal */
  34266. void focusGained (FocusChangeType cause);
  34267. /** @internal */
  34268. void focusLost (FocusChangeType cause);
  34269. /** @internal */
  34270. void enablementChanged();
  34271. /** @internal */
  34272. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo&);
  34273. /** @internal */
  34274. void applicationCommandListChanged();
  34275. /** @internal */
  34276. void valueChanged (Value& value);
  34277. private:
  34278. Array <KeyPress> shortcuts;
  34279. WeakReference<Component> keySource;
  34280. String text;
  34281. ListenerList <Listener> buttonListeners;
  34282. class RepeatTimer;
  34283. friend class RepeatTimer;
  34284. friend class ScopedPointer <RepeatTimer>;
  34285. ScopedPointer <RepeatTimer> repeatTimer;
  34286. uint32 buttonPressTime, lastRepeatTime;
  34287. ApplicationCommandManager* commandManagerToUse;
  34288. int autoRepeatDelay, autoRepeatSpeed, autoRepeatMinimumDelay;
  34289. int radioGroupId, commandID, connectedEdgeFlags;
  34290. ButtonState buttonState;
  34291. Value isOn;
  34292. bool lastToggleState : 1;
  34293. bool clickTogglesState : 1;
  34294. bool needsToRelease : 1;
  34295. bool needsRepainting : 1;
  34296. bool isKeyDown : 1;
  34297. bool triggerOnMouseDown : 1;
  34298. bool generateTooltip : 1;
  34299. void repeatTimerCallback();
  34300. RepeatTimer& getRepeatTimer();
  34301. ButtonState updateState();
  34302. ButtonState updateState (bool isOver, bool isDown);
  34303. bool isShortcutPressed() const;
  34304. void turnOffOtherButtonsInGroup (bool sendChangeNotification);
  34305. void flashButtonState();
  34306. void sendClickMessage (const ModifierKeys& modifiers);
  34307. void sendStateMessage();
  34308. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Button);
  34309. };
  34310. #ifndef DOXYGEN
  34311. /** This typedef is just for compatibility with old code and VC6 - newer code should use Button::Listener instead. */
  34312. typedef Button::Listener ButtonListener;
  34313. #endif
  34314. #if JUCE_VC6
  34315. #undef Listener
  34316. #endif
  34317. #endif // __JUCE_BUTTON_JUCEHEADER__
  34318. /*** End of inlined file: juce_Button.h ***/
  34319. /**
  34320. A scrollbar component.
  34321. To use a scrollbar, set up its total range using the setRangeLimits() method - this
  34322. sets the range of values it can represent. Then you can use setCurrentRange() to
  34323. change the position and size of the scrollbar's 'thumb'.
  34324. Registering a ScrollBar::Listener with the scrollbar will allow you to find out when
  34325. the user moves it, and you can use the getCurrentRangeStart() to find out where
  34326. they moved it to.
  34327. The scrollbar will adjust its own visibility according to whether its thumb size
  34328. allows it to actually be scrolled.
  34329. For most purposes, it's probably easier to use a ViewportContainer or ListBox
  34330. instead of handling a scrollbar directly.
  34331. @see ScrollBar::Listener
  34332. */
  34333. class JUCE_API ScrollBar : public Component,
  34334. public AsyncUpdater,
  34335. private Timer
  34336. {
  34337. public:
  34338. /** Creates a Scrollbar.
  34339. @param isVertical whether it should be a vertical or horizontal bar
  34340. @param buttonsAreVisible whether to show the up/down or left/right buttons
  34341. */
  34342. ScrollBar (bool isVertical,
  34343. bool buttonsAreVisible = true);
  34344. /** Destructor. */
  34345. ~ScrollBar();
  34346. /** Returns true if the scrollbar is vertical, false if it's horizontal. */
  34347. bool isVertical() const noexcept { return vertical; }
  34348. /** Changes the scrollbar's direction.
  34349. You'll also need to resize the bar appropriately - this just changes its internal
  34350. layout.
  34351. @param shouldBeVertical true makes it vertical; false makes it horizontal.
  34352. */
  34353. void setOrientation (bool shouldBeVertical);
  34354. /** Shows or hides the scrollbar's buttons. */
  34355. void setButtonVisibility (bool buttonsAreVisible);
  34356. /** Tells the scrollbar whether to make itself invisible when not needed.
  34357. The default behaviour is for a scrollbar to become invisible when the thumb
  34358. fills the whole of its range (i.e. when it can't be moved). Setting this
  34359. value to false forces the bar to always be visible.
  34360. @see autoHides()
  34361. */
  34362. void setAutoHide (bool shouldHideWhenFullRange);
  34363. /** Returns true if this scrollbar is set to auto-hide when its thumb is as big
  34364. as its maximum range.
  34365. @see setAutoHide
  34366. */
  34367. bool autoHides() const noexcept;
  34368. /** Sets the minimum and maximum values that the bar will move between.
  34369. The bar's thumb will always be constrained so that the entire thumb lies
  34370. within this range.
  34371. @see setCurrentRange
  34372. */
  34373. void setRangeLimits (const Range<double>& newRangeLimit);
  34374. /** Sets the minimum and maximum values that the bar will move between.
  34375. The bar's thumb will always be constrained so that the entire thumb lies
  34376. within this range.
  34377. @see setCurrentRange
  34378. */
  34379. void setRangeLimits (double minimum, double maximum);
  34380. /** Returns the current limits on the thumb position.
  34381. @see setRangeLimits
  34382. */
  34383. const Range<double> getRangeLimit() const noexcept { return totalRange; }
  34384. /** Returns the lower value that the thumb can be set to.
  34385. This is the value set by setRangeLimits().
  34386. */
  34387. double getMinimumRangeLimit() const noexcept { return totalRange.getStart(); }
  34388. /** Returns the upper value that the thumb can be set to.
  34389. This is the value set by setRangeLimits().
  34390. */
  34391. double getMaximumRangeLimit() const noexcept { return totalRange.getEnd(); }
  34392. /** Changes the position of the scrollbar's 'thumb'.
  34393. If this method call actually changes the scrollbar's position, it will trigger an
  34394. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  34395. are registered.
  34396. @see getCurrentRange. setCurrentRangeStart
  34397. */
  34398. void setCurrentRange (const Range<double>& newRange);
  34399. /** Changes the position of the scrollbar's 'thumb'.
  34400. This sets both the position and size of the thumb - to just set the position without
  34401. changing the size, you can use setCurrentRangeStart().
  34402. If this method call actually changes the scrollbar's position, it will trigger an
  34403. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  34404. are registered.
  34405. @param newStart the top (or left) of the thumb, in the range
  34406. getMinimumRangeLimit() <= newStart <= getMaximumRangeLimit(). If the
  34407. value is beyond these limits, it will be clipped.
  34408. @param newSize the size of the thumb, such that
  34409. getMinimumRangeLimit() <= newStart + newSize <= getMaximumRangeLimit(). If the
  34410. size is beyond these limits, it will be clipped.
  34411. @see setCurrentRangeStart, getCurrentRangeStart, getCurrentRangeSize
  34412. */
  34413. void setCurrentRange (double newStart, double newSize);
  34414. /** Moves the bar's thumb position.
  34415. This will move the thumb position without changing the thumb size. Note
  34416. that the maximum thumb start position is (getMaximumRangeLimit() - getCurrentRangeSize()).
  34417. If this method call actually changes the scrollbar's position, it will trigger an
  34418. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  34419. are registered.
  34420. @see setCurrentRange
  34421. */
  34422. void setCurrentRangeStart (double newStart);
  34423. /** Returns the current thumb range.
  34424. @see getCurrentRange, setCurrentRange
  34425. */
  34426. const Range<double> getCurrentRange() const noexcept { return visibleRange; }
  34427. /** Returns the position of the top of the thumb.
  34428. @see getCurrentRange, setCurrentRangeStart
  34429. */
  34430. double getCurrentRangeStart() const noexcept { return visibleRange.getStart(); }
  34431. /** Returns the current size of the thumb.
  34432. @see getCurrentRange, setCurrentRange
  34433. */
  34434. double getCurrentRangeSize() const noexcept { return visibleRange.getLength(); }
  34435. /** Sets the amount by which the up and down buttons will move the bar.
  34436. The value here is in terms of the total range, and is added or subtracted
  34437. from the thumb position when the user clicks an up/down (or left/right) button.
  34438. */
  34439. void setSingleStepSize (double newSingleStepSize);
  34440. /** Moves the scrollbar by a number of single-steps.
  34441. This will move the bar by a multiple of its single-step interval (as
  34442. specified using the setSingleStepSize() method).
  34443. A positive value here will move the bar down or to the right, a negative
  34444. value moves it up or to the left.
  34445. */
  34446. void moveScrollbarInSteps (int howManySteps);
  34447. /** Moves the scroll bar up or down in pages.
  34448. This will move the bar by a multiple of its current thumb size, effectively
  34449. doing a page-up or down.
  34450. A positive value here will move the bar down or to the right, a negative
  34451. value moves it up or to the left.
  34452. */
  34453. void moveScrollbarInPages (int howManyPages);
  34454. /** Scrolls to the top (or left).
  34455. This is the same as calling setCurrentRangeStart (getMinimumRangeLimit());
  34456. */
  34457. void scrollToTop();
  34458. /** Scrolls to the bottom (or right).
  34459. This is the same as calling setCurrentRangeStart (getMaximumRangeLimit() - getCurrentRangeSize());
  34460. */
  34461. void scrollToBottom();
  34462. /** Changes the delay before the up and down buttons autorepeat when they are held
  34463. down.
  34464. For an explanation of what the parameters are for, see Button::setRepeatSpeed().
  34465. @see Button::setRepeatSpeed
  34466. */
  34467. void setButtonRepeatSpeed (int initialDelayInMillisecs,
  34468. int repeatDelayInMillisecs,
  34469. int minimumDelayInMillisecs = -1);
  34470. /** A set of colour IDs to use to change the colour of various aspects of the component.
  34471. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34472. methods.
  34473. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34474. */
  34475. enum ColourIds
  34476. {
  34477. backgroundColourId = 0x1000300, /**< The background colour of the scrollbar. */
  34478. thumbColourId = 0x1000400, /**< A base colour to use for the thumb. The look and feel will probably use variations on this colour. */
  34479. 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. */
  34480. };
  34481. /**
  34482. A class for receiving events from a ScrollBar.
  34483. You can register a ScrollBar::Listener with a ScrollBar using the ScrollBar::addListener()
  34484. method, and it will be called when the bar's position changes.
  34485. @see ScrollBar::addListener, ScrollBar::removeListener
  34486. */
  34487. class JUCE_API Listener
  34488. {
  34489. public:
  34490. /** Destructor. */
  34491. virtual ~Listener() {}
  34492. /** Called when a ScrollBar is moved.
  34493. @param scrollBarThatHasMoved the bar that has moved
  34494. @param newRangeStart the new range start of this bar
  34495. */
  34496. virtual void scrollBarMoved (ScrollBar* scrollBarThatHasMoved,
  34497. double newRangeStart) = 0;
  34498. };
  34499. /** Registers a listener that will be called when the scrollbar is moved. */
  34500. void addListener (Listener* listener);
  34501. /** Deregisters a previously-registered listener. */
  34502. void removeListener (Listener* listener);
  34503. /** @internal */
  34504. bool keyPressed (const KeyPress& key);
  34505. /** @internal */
  34506. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  34507. /** @internal */
  34508. void lookAndFeelChanged();
  34509. /** @internal */
  34510. void handleAsyncUpdate();
  34511. /** @internal */
  34512. void mouseDown (const MouseEvent& e);
  34513. /** @internal */
  34514. void mouseDrag (const MouseEvent& e);
  34515. /** @internal */
  34516. void mouseUp (const MouseEvent& e);
  34517. /** @internal */
  34518. void paint (Graphics& g);
  34519. /** @internal */
  34520. void resized();
  34521. private:
  34522. Range <double> totalRange, visibleRange;
  34523. double singleStepSize, dragStartRange;
  34524. int thumbAreaStart, thumbAreaSize, thumbStart, thumbSize;
  34525. int dragStartMousePos, lastMousePos;
  34526. int initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs;
  34527. bool vertical, isDraggingThumb, autohides;
  34528. class ScrollbarButton;
  34529. friend class ScopedPointer<ScrollbarButton>;
  34530. ScopedPointer<ScrollbarButton> upButton, downButton;
  34531. ListenerList <Listener> listeners;
  34532. void updateThumbPosition();
  34533. void timerCallback();
  34534. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ScrollBar);
  34535. };
  34536. /** This typedef is just for compatibility with old code - newer code should use the ScrollBar::Listener class directly. */
  34537. typedef ScrollBar::Listener ScrollBarListener;
  34538. #endif // __JUCE_SCROLLBAR_JUCEHEADER__
  34539. /*** End of inlined file: juce_ScrollBar.h ***/
  34540. /**
  34541. A Viewport is used to contain a larger child component, and allows the child
  34542. to be automatically scrolled around.
  34543. To use a Viewport, just create one and set the component that goes inside it
  34544. using the setViewedComponent() method. When the child component changes size,
  34545. the Viewport will adjust its scrollbars accordingly.
  34546. A subclass of the viewport can be created which will receive calls to its
  34547. visibleAreaChanged() method when the subcomponent changes position or size.
  34548. */
  34549. class JUCE_API Viewport : public Component,
  34550. private ComponentListener,
  34551. private ScrollBar::Listener
  34552. {
  34553. public:
  34554. /** Creates a Viewport.
  34555. The viewport is initially empty - use the setViewedComponent() method to
  34556. add a child component for it to manage.
  34557. */
  34558. explicit Viewport (const String& componentName = String::empty);
  34559. /** Destructor. */
  34560. ~Viewport();
  34561. /** Sets the component that this viewport will contain and scroll around.
  34562. This will add the given component to this Viewport and position it at (0, 0).
  34563. (Don't add or remove any child components directly using the normal
  34564. Component::addChildComponent() methods).
  34565. @param newViewedComponent the component to add to this viewport, or null to remove
  34566. the current component.
  34567. @param deleteComponentWhenNoLongerNeeded if true, the component will be deleted
  34568. automatically when the viewport is deleted or when a different
  34569. component is added. If false, the caller must manage the lifetime
  34570. of the component
  34571. @see getViewedComponent
  34572. */
  34573. void setViewedComponent (Component* newViewedComponent,
  34574. bool deleteComponentWhenNoLongerNeeded = true);
  34575. /** Returns the component that's currently being used inside the Viewport.
  34576. @see setViewedComponent
  34577. */
  34578. Component* getViewedComponent() const noexcept { return contentComp; }
  34579. /** Changes the position of the viewed component.
  34580. The inner component will be moved so that the pixel at the top left of
  34581. the viewport will be the pixel at position (xPixelsOffset, yPixelsOffset)
  34582. within the inner component.
  34583. This will update the scrollbars and might cause a call to visibleAreaChanged().
  34584. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  34585. */
  34586. void setViewPosition (int xPixelsOffset, int yPixelsOffset);
  34587. /** Changes the position of the viewed component.
  34588. The inner component will be moved so that the pixel at the top left of
  34589. the viewport will be the pixel at the specified coordinates within the
  34590. inner component.
  34591. This will update the scrollbars and might cause a call to visibleAreaChanged().
  34592. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  34593. */
  34594. void setViewPosition (const Point<int>& newPosition);
  34595. /** Changes the view position as a proportion of the distance it can move.
  34596. The values here are from 0.0 to 1.0 - where (0, 0) would put the
  34597. visible area in the top-left, and (1, 1) would put it as far down and
  34598. to the right as it's possible to go whilst keeping the child component
  34599. on-screen.
  34600. */
  34601. void setViewPositionProportionately (double proportionX, double proportionY);
  34602. /** If the specified position is at the edges of the viewport, this method scrolls
  34603. the viewport to bring that position nearer to the centre.
  34604. Call this if you're dragging an object inside a viewport and want to make it scroll
  34605. when the user approaches an edge. You might also find Component::beginDragAutoRepeat()
  34606. useful when auto-scrolling.
  34607. @param mouseX the x position, relative to the Viewport's top-left
  34608. @param mouseY the y position, relative to the Viewport's top-left
  34609. @param distanceFromEdge specifies how close to an edge the position needs to be
  34610. before the viewport should scroll in that direction
  34611. @param maximumSpeed the maximum number of pixels that the viewport is allowed
  34612. to scroll by.
  34613. @returns true if the viewport was scrolled
  34614. */
  34615. bool autoScroll (int mouseX, int mouseY, int distanceFromEdge, int maximumSpeed);
  34616. /** Returns the position within the child component of the top-left of its visible area.
  34617. */
  34618. const Point<int> getViewPosition() const noexcept { return lastVisibleArea.getPosition(); }
  34619. /** Returns the position within the child component of the top-left of its visible area.
  34620. @see getViewWidth, setViewPosition
  34621. */
  34622. int getViewPositionX() const noexcept { return lastVisibleArea.getX(); }
  34623. /** Returns the position within the child component of the top-left of its visible area.
  34624. @see getViewHeight, setViewPosition
  34625. */
  34626. int getViewPositionY() const noexcept { return lastVisibleArea.getY(); }
  34627. /** Returns the width of the visible area of the child component.
  34628. This may be less than the width of this Viewport if there's a vertical scrollbar
  34629. or if the child component is itself smaller.
  34630. */
  34631. int getViewWidth() const noexcept { return lastVisibleArea.getWidth(); }
  34632. /** Returns the height of the visible area of the child component.
  34633. This may be less than the height of this Viewport if there's a horizontal scrollbar
  34634. or if the child component is itself smaller.
  34635. */
  34636. int getViewHeight() const noexcept { return lastVisibleArea.getHeight(); }
  34637. /** Returns the width available within this component for the contents.
  34638. This will be the width of the viewport component minus the width of a
  34639. vertical scrollbar (if visible).
  34640. */
  34641. int getMaximumVisibleWidth() const;
  34642. /** Returns the height available within this component for the contents.
  34643. This will be the height of the viewport component minus the space taken up
  34644. by a horizontal scrollbar (if visible).
  34645. */
  34646. int getMaximumVisibleHeight() const;
  34647. /** Callback method that is called when the visible area changes.
  34648. This will be called when the visible area is moved either be scrolling or
  34649. by calls to setViewPosition(), etc.
  34650. */
  34651. virtual void visibleAreaChanged (const Rectangle<int>& newVisibleArea);
  34652. /** Turns scrollbars on or off.
  34653. If set to false, the scrollbars won't ever appear. When true (the default)
  34654. they will appear only when needed.
  34655. */
  34656. void setScrollBarsShown (bool showVerticalScrollbarIfNeeded,
  34657. bool showHorizontalScrollbarIfNeeded);
  34658. /** True if the vertical scrollbar is enabled.
  34659. @see setScrollBarsShown
  34660. */
  34661. bool isVerticalScrollBarShown() const noexcept { return showVScrollbar; }
  34662. /** True if the horizontal scrollbar is enabled.
  34663. @see setScrollBarsShown
  34664. */
  34665. bool isHorizontalScrollBarShown() const noexcept { return showHScrollbar; }
  34666. /** Changes the width of the scrollbars.
  34667. If this isn't specified, the default width from the LookAndFeel class will be used.
  34668. @see LookAndFeel::getDefaultScrollbarWidth
  34669. */
  34670. void setScrollBarThickness (int thickness);
  34671. /** Returns the thickness of the scrollbars.
  34672. @see setScrollBarThickness
  34673. */
  34674. int getScrollBarThickness() const;
  34675. /** Changes the distance that a single-step click on a scrollbar button
  34676. will move the viewport.
  34677. */
  34678. void setSingleStepSizes (int stepX, int stepY);
  34679. /** Shows or hides the buttons on any scrollbars that are used.
  34680. @see ScrollBar::setButtonVisibility
  34681. */
  34682. void setScrollBarButtonVisibility (bool buttonsVisible);
  34683. /** Returns a pointer to the scrollbar component being used.
  34684. Handy if you need to customise the bar somehow.
  34685. */
  34686. ScrollBar* getVerticalScrollBar() noexcept { return &verticalScrollBar; }
  34687. /** Returns a pointer to the scrollbar component being used.
  34688. Handy if you need to customise the bar somehow.
  34689. */
  34690. ScrollBar* getHorizontalScrollBar() noexcept { return &horizontalScrollBar; }
  34691. /** @internal */
  34692. void resized();
  34693. /** @internal */
  34694. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  34695. /** @internal */
  34696. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  34697. /** @internal */
  34698. bool keyPressed (const KeyPress& key);
  34699. /** @internal */
  34700. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  34701. /** @internal */
  34702. bool useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  34703. private:
  34704. WeakReference<Component> contentComp;
  34705. Rectangle<int> lastVisibleArea;
  34706. int scrollBarThickness;
  34707. int singleStepX, singleStepY;
  34708. bool showHScrollbar, showVScrollbar, deleteContent;
  34709. Component contentHolder;
  34710. ScrollBar verticalScrollBar;
  34711. ScrollBar horizontalScrollBar;
  34712. void updateVisibleArea();
  34713. void deleteContentComp();
  34714. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  34715. // If you get an error here, it's because this method's parameters have changed! See the new definition above..
  34716. virtual int visibleAreaChanged (int, int, int, int) { return 0; }
  34717. #endif
  34718. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Viewport);
  34719. };
  34720. #endif // __JUCE_VIEWPORT_JUCEHEADER__
  34721. /*** End of inlined file: juce_Viewport.h ***/
  34722. class ListViewport;
  34723. /**
  34724. A subclass of this is used to drive a ListBox.
  34725. @see ListBox
  34726. */
  34727. class JUCE_API ListBoxModel
  34728. {
  34729. public:
  34730. /** Destructor. */
  34731. virtual ~ListBoxModel() {}
  34732. /** This has to return the number of items in the list.
  34733. @see ListBox::getNumRows()
  34734. */
  34735. virtual int getNumRows() = 0;
  34736. /** This method must be implemented to draw a row of the list.
  34737. */
  34738. virtual void paintListBoxItem (int rowNumber,
  34739. Graphics& g,
  34740. int width, int height,
  34741. bool rowIsSelected) = 0;
  34742. /** This is used to create or update a custom component to go in a row of the list.
  34743. Any row may contain a custom component, or can just be drawn with the paintListBoxItem() method
  34744. and handle mouse clicks with listBoxItemClicked().
  34745. This method will be called whenever a custom component might need to be updated - e.g.
  34746. when the table is changed, or TableListBox::updateContent() is called.
  34747. If you don't need a custom component for the specified row, then return 0.
  34748. If you do want a custom component, and the existingComponentToUpdate is null, then
  34749. this method must create a suitable new component and return it.
  34750. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  34751. by this method. In this case, the method must either update it to make sure it's correctly representing
  34752. the given row (which may be different from the one that the component was created for), or it can
  34753. delete this component and return a new one.
  34754. The component that your method returns will be deleted by the ListBox when it is no longer needed.
  34755. */
  34756. virtual Component* refreshComponentForRow (int rowNumber, bool isRowSelected,
  34757. Component* existingComponentToUpdate);
  34758. /** This can be overridden to react to the user clicking on a row.
  34759. @see listBoxItemDoubleClicked
  34760. */
  34761. virtual void listBoxItemClicked (int row, const MouseEvent& e);
  34762. /** This can be overridden to react to the user double-clicking on a row.
  34763. @see listBoxItemClicked
  34764. */
  34765. virtual void listBoxItemDoubleClicked (int row, const MouseEvent& e);
  34766. /** This can be overridden to react to the user double-clicking on a part of the list where
  34767. there are no rows.
  34768. @see listBoxItemClicked
  34769. */
  34770. virtual void backgroundClicked();
  34771. /** Override this to be informed when rows are selected or deselected.
  34772. This will be called whenever a row is selected or deselected. If a range of
  34773. rows is selected all at once, this will just be called once for that event.
  34774. @param lastRowSelected the last row that the user selected. If no
  34775. rows are currently selected, this may be -1.
  34776. */
  34777. virtual void selectedRowsChanged (int lastRowSelected);
  34778. /** Override this to be informed when the delete key is pressed.
  34779. If no rows are selected when they press the key, this won't be called.
  34780. @param lastRowSelected the last row that had been selected when they pressed the
  34781. key - if there are multiple selections, this might not be
  34782. very useful
  34783. */
  34784. virtual void deleteKeyPressed (int lastRowSelected);
  34785. /** Override this to be informed when the return key is pressed.
  34786. If no rows are selected when they press the key, this won't be called.
  34787. @param lastRowSelected the last row that had been selected when they pressed the
  34788. key - if there are multiple selections, this might not be
  34789. very useful
  34790. */
  34791. virtual void returnKeyPressed (int lastRowSelected);
  34792. /** Override this to be informed when the list is scrolled.
  34793. This might be caused by the user moving the scrollbar, or by programmatic changes
  34794. to the list position.
  34795. */
  34796. virtual void listWasScrolled();
  34797. /** To allow rows from your list to be dragged-and-dropped, implement this method.
  34798. If this returns a non-null variant then when the user drags a row, the listbox will
  34799. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  34800. a drag-and-drop operation, using this string as the source description, with the listbox
  34801. itself as the source component.
  34802. @see DragAndDropContainer::startDragging
  34803. */
  34804. virtual const var getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  34805. /** You can override this to provide tool tips for specific rows.
  34806. @see TooltipClient
  34807. */
  34808. virtual const String getTooltipForRow (int row);
  34809. };
  34810. /**
  34811. A list of items that can be scrolled vertically.
  34812. To create a list, you'll need to create a subclass of ListBoxModel. This can
  34813. either paint each row of the list and respond to events via callbacks, or for
  34814. more specialised tasks, it can supply a custom component to fill each row.
  34815. @see ComboBox, TableListBox
  34816. */
  34817. class JUCE_API ListBox : public Component,
  34818. public SettableTooltipClient
  34819. {
  34820. public:
  34821. /** Creates a ListBox.
  34822. The model pointer passed-in can be null, in which case you can set it later
  34823. with setModel().
  34824. */
  34825. ListBox (const String& componentName = String::empty,
  34826. ListBoxModel* model = 0);
  34827. /** Destructor. */
  34828. ~ListBox();
  34829. /** Changes the current data model to display. */
  34830. void setModel (ListBoxModel* newModel);
  34831. /** Returns the current list model. */
  34832. ListBoxModel* getModel() const noexcept { return model; }
  34833. /** Causes the list to refresh its content.
  34834. Call this when the number of rows in the list changes, or if you want it
  34835. to call refreshComponentForRow() on all the row components.
  34836. This must only be called from the main message thread.
  34837. */
  34838. void updateContent();
  34839. /** Turns on multiple-selection of rows.
  34840. By default this is disabled.
  34841. When your row component gets clicked you'll need to call the
  34842. selectRowsBasedOnModifierKeys() method to tell the list that it's been
  34843. clicked and to get it to do the appropriate selection based on whether
  34844. the ctrl/shift keys are held down.
  34845. */
  34846. void setMultipleSelectionEnabled (bool shouldBeEnabled);
  34847. /** Makes the list react to mouse moves by selecting the row that the mouse if over.
  34848. This function is here primarily for the ComboBox class to use, but might be
  34849. useful for some other purpose too.
  34850. */
  34851. void setMouseMoveSelectsRows (bool shouldSelect);
  34852. /** Selects a row.
  34853. If the row is already selected, this won't do anything.
  34854. @param rowNumber the row to select
  34855. @param dontScrollToShowThisRow if true, the list's position won't change; if false and
  34856. the selected row is off-screen, it'll scroll to make
  34857. sure that row is on-screen
  34858. @param deselectOthersFirst if true and there are multiple selections, these will
  34859. first be deselected before this item is selected
  34860. @see isRowSelected, selectRowsBasedOnModifierKeys, flipRowSelection, deselectRow,
  34861. deselectAllRows, selectRangeOfRows
  34862. */
  34863. void selectRow (int rowNumber,
  34864. bool dontScrollToShowThisRow = false,
  34865. bool deselectOthersFirst = true);
  34866. /** Selects a set of rows.
  34867. This will add these rows to the current selection, so you might need to
  34868. clear the current selection first with deselectAllRows()
  34869. @param firstRow the first row to select (inclusive)
  34870. @param lastRow the last row to select (inclusive)
  34871. */
  34872. void selectRangeOfRows (int firstRow,
  34873. int lastRow);
  34874. /** Deselects a row.
  34875. If it's not currently selected, this will do nothing.
  34876. @see selectRow, deselectAllRows
  34877. */
  34878. void deselectRow (int rowNumber);
  34879. /** Deselects any currently selected rows.
  34880. @see deselectRow
  34881. */
  34882. void deselectAllRows();
  34883. /** Selects or deselects a row.
  34884. If the row's currently selected, this deselects it, and vice-versa.
  34885. */
  34886. void flipRowSelection (int rowNumber);
  34887. /** Returns a sparse set indicating the rows that are currently selected.
  34888. @see setSelectedRows
  34889. */
  34890. const SparseSet<int> getSelectedRows() const;
  34891. /** Sets the rows that should be selected, based on an explicit set of ranges.
  34892. If sendNotificationEventToModel is true, the ListBoxModel::selectedRowsChanged()
  34893. method will be called. If it's false, no notification will be sent to the model.
  34894. @see getSelectedRows
  34895. */
  34896. void setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  34897. bool sendNotificationEventToModel = true);
  34898. /** Checks whether a row is selected.
  34899. */
  34900. bool isRowSelected (int rowNumber) const;
  34901. /** Returns the number of rows that are currently selected.
  34902. @see getSelectedRow, isRowSelected, getLastRowSelected
  34903. */
  34904. int getNumSelectedRows() const;
  34905. /** Returns the row number of a selected row.
  34906. This will return the row number of the Nth selected row. The row numbers returned will
  34907. be sorted in order from low to high.
  34908. @param index the index of the selected row to return, (from 0 to getNumSelectedRows() - 1)
  34909. @returns the row number, or -1 if the index was out of range or if there aren't any rows
  34910. selected
  34911. @see getNumSelectedRows, isRowSelected, getLastRowSelected
  34912. */
  34913. int getSelectedRow (int index = 0) const;
  34914. /** Returns the last row that the user selected.
  34915. This isn't the same as the highest row number that is currently selected - if the user
  34916. had multiply-selected rows 10, 5 and then 6 in that order, this would return 6.
  34917. If nothing is selected, it will return -1.
  34918. */
  34919. int getLastRowSelected() const;
  34920. /** Multiply-selects rows based on the modifier keys.
  34921. If no modifier keys are down, this will select the given row and
  34922. deselect any others.
  34923. If the ctrl (or command on the Mac) key is down, it'll flip the
  34924. state of the selected row.
  34925. If the shift key is down, it'll select up to the given row from the
  34926. last row selected.
  34927. @see selectRow
  34928. */
  34929. void selectRowsBasedOnModifierKeys (int rowThatWasClickedOn,
  34930. const ModifierKeys& modifiers,
  34931. bool isMouseUpEvent);
  34932. /** Scrolls the list to a particular position.
  34933. The proportion is between 0 and 1.0, so 0 scrolls to the top of the list,
  34934. 1.0 scrolls to the bottom.
  34935. If the total number of rows all fit onto the screen at once, then this
  34936. method won't do anything.
  34937. @see getVerticalPosition
  34938. */
  34939. void setVerticalPosition (double newProportion);
  34940. /** Returns the current vertical position as a proportion of the total.
  34941. This can be used in conjunction with setVerticalPosition() to save and restore
  34942. the list's position. It returns a value in the range 0 to 1.
  34943. @see setVerticalPosition
  34944. */
  34945. double getVerticalPosition() const;
  34946. /** Scrolls if necessary to make sure that a particular row is visible.
  34947. */
  34948. void scrollToEnsureRowIsOnscreen (int row);
  34949. /** Returns a pointer to the scrollbar.
  34950. (Unlikely to be useful for most people).
  34951. */
  34952. ScrollBar* getVerticalScrollBar() const noexcept;
  34953. /** Returns a pointer to the scrollbar.
  34954. (Unlikely to be useful for most people).
  34955. */
  34956. ScrollBar* getHorizontalScrollBar() const noexcept;
  34957. /** Finds the row index that contains a given x,y position.
  34958. The position is relative to the ListBox's top-left.
  34959. If no row exists at this position, the method will return -1.
  34960. @see getComponentForRowNumber
  34961. */
  34962. int getRowContainingPosition (int x, int y) const noexcept;
  34963. /** Finds a row index that would be the most suitable place to insert a new
  34964. item for a given position.
  34965. This is useful when the user is e.g. dragging and dropping onto the listbox,
  34966. because it lets you easily choose the best position to insert the item that
  34967. they drop, based on where they drop it.
  34968. If the position is out of range, this will return -1. If the position is
  34969. beyond the end of the list, it will return getNumRows() to indicate the end
  34970. of the list.
  34971. @see getComponentForRowNumber
  34972. */
  34973. int getInsertionIndexForPosition (int x, int y) const noexcept;
  34974. /** Returns the position of one of the rows, relative to the top-left of
  34975. the listbox.
  34976. This may be off-screen, and the range of the row number that is passed-in is
  34977. not checked to see if it's a valid row.
  34978. */
  34979. const Rectangle<int> getRowPosition (int rowNumber,
  34980. bool relativeToComponentTopLeft) const noexcept;
  34981. /** Finds the row component for a given row in the list.
  34982. The component returned will have been created using createRowComponent().
  34983. If the component for this row is off-screen or if the row is out-of-range,
  34984. this will return 0.
  34985. @see getRowContainingPosition
  34986. */
  34987. Component* getComponentForRowNumber (int rowNumber) const noexcept;
  34988. /** Returns the row number that the given component represents.
  34989. If the component isn't one of the list's rows, this will return -1.
  34990. */
  34991. int getRowNumberOfComponent (Component* rowComponent) const noexcept;
  34992. /** Returns the width of a row (which may be less than the width of this component
  34993. if there's a scrollbar).
  34994. */
  34995. int getVisibleRowWidth() const noexcept;
  34996. /** Sets the height of each row in the list.
  34997. The default height is 22 pixels.
  34998. @see getRowHeight
  34999. */
  35000. void setRowHeight (int newHeight);
  35001. /** Returns the height of a row in the list.
  35002. @see setRowHeight
  35003. */
  35004. int getRowHeight() const noexcept { return rowHeight; }
  35005. /** Returns the number of rows actually visible.
  35006. This is the number of whole rows which will fit on-screen, so the value might
  35007. be more than the actual number of rows in the list.
  35008. */
  35009. int getNumRowsOnScreen() const noexcept;
  35010. /** A set of colour IDs to use to change the colour of various aspects of the label.
  35011. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35012. methods.
  35013. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35014. */
  35015. enum ColourIds
  35016. {
  35017. backgroundColourId = 0x1002800, /**< The background colour to fill the list with.
  35018. Make this transparent if you don't want the background to be filled. */
  35019. outlineColourId = 0x1002810, /**< An optional colour to use to draw a border around the list.
  35020. Make this transparent to not have an outline. */
  35021. textColourId = 0x1002820 /**< The preferred colour to use for drawing text in the listbox. */
  35022. };
  35023. /** Sets the thickness of a border that will be drawn around the box.
  35024. To set the colour of the outline, use @code setColour (ListBox::outlineColourId, colourXYZ); @endcode
  35025. @see outlineColourId
  35026. */
  35027. void setOutlineThickness (int outlineThickness);
  35028. /** Returns the thickness of outline that will be drawn around the listbox.
  35029. @see setOutlineColour
  35030. */
  35031. int getOutlineThickness() const noexcept { return outlineThickness; }
  35032. /** Sets a component that the list should use as a header.
  35033. This will position the given component at the top of the list, maintaining the
  35034. height of the component passed-in, but rescaling it horizontally to match the
  35035. width of the items in the listbox.
  35036. The component will be deleted when setHeaderComponent() is called with a
  35037. different component, or when the listbox is deleted.
  35038. */
  35039. void setHeaderComponent (Component* newHeaderComponent);
  35040. /** Changes the width of the rows in the list.
  35041. This can be used to make the list's row components wider than the list itself - the
  35042. width of the rows will be either the width of the list or this value, whichever is
  35043. greater, and if the rows become wider than the list, a horizontal scrollbar will
  35044. appear.
  35045. The default value for this is 0, which means that the rows will always
  35046. be the same width as the list.
  35047. */
  35048. void setMinimumContentWidth (int newMinimumWidth);
  35049. /** Returns the space currently available for the row items, taking into account
  35050. borders, scrollbars, etc.
  35051. */
  35052. int getVisibleContentWidth() const noexcept;
  35053. /** Repaints one of the rows.
  35054. This is a lightweight alternative to calling updateContent, and just causes a
  35055. repaint of the row's area.
  35056. */
  35057. void repaintRow (int rowNumber) noexcept;
  35058. /** This fairly obscure method creates an image that just shows the currently
  35059. selected row components.
  35060. It's a handy method for doing drag-and-drop, as it can be passed to the
  35061. DragAndDropContainer for use as the drag image.
  35062. Note that it will make the row components temporarily invisible, so if you're
  35063. using custom components this could affect them if they're sensitive to that
  35064. sort of thing.
  35065. @see Component::createComponentSnapshot
  35066. */
  35067. virtual const Image createSnapshotOfSelectedRows (int& x, int& y);
  35068. /** Returns the viewport that this ListBox uses.
  35069. You may need to use this to change parameters such as whether scrollbars
  35070. are shown, etc.
  35071. */
  35072. Viewport* getViewport() const noexcept;
  35073. /** @internal */
  35074. bool keyPressed (const KeyPress& key);
  35075. /** @internal */
  35076. bool keyStateChanged (bool isKeyDown);
  35077. /** @internal */
  35078. void paint (Graphics& g);
  35079. /** @internal */
  35080. void paintOverChildren (Graphics& g);
  35081. /** @internal */
  35082. void resized();
  35083. /** @internal */
  35084. void visibilityChanged();
  35085. /** @internal */
  35086. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  35087. /** @internal */
  35088. void mouseMove (const MouseEvent&);
  35089. /** @internal */
  35090. void mouseExit (const MouseEvent&);
  35091. /** @internal */
  35092. void mouseUp (const MouseEvent&);
  35093. /** @internal */
  35094. void colourChanged();
  35095. /** @internal */
  35096. void startDragAndDrop (const MouseEvent& e, const var& dragDescription, bool allowDraggingToOtherWindows = true);
  35097. private:
  35098. friend class ListViewport;
  35099. friend class TableListBox;
  35100. ListBoxModel* model;
  35101. ScopedPointer<ListViewport> viewport;
  35102. ScopedPointer<Component> headerComponent;
  35103. int totalItems, rowHeight, minimumRowWidth;
  35104. int outlineThickness;
  35105. int lastRowSelected;
  35106. bool mouseMoveSelects, multipleSelection, hasDoneInitialUpdate;
  35107. SparseSet <int> selected;
  35108. void selectRowInternal (int rowNumber,
  35109. bool dontScrollToShowThisRow,
  35110. bool deselectOthersFirst,
  35111. bool isMouseClick);
  35112. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListBox);
  35113. };
  35114. #endif // __JUCE_LISTBOX_JUCEHEADER__
  35115. /*** End of inlined file: juce_ListBox.h ***/
  35116. /*** Start of inlined file: juce_TextButton.h ***/
  35117. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  35118. #define __JUCE_TEXTBUTTON_JUCEHEADER__
  35119. /**
  35120. A button that uses the standard lozenge-shaped background with a line of
  35121. text on it.
  35122. @see Button, DrawableButton
  35123. */
  35124. class JUCE_API TextButton : public Button
  35125. {
  35126. public:
  35127. /** Creates a TextButton.
  35128. @param buttonName the text to put in the button (the component's name is also
  35129. initially set to this string, but these can be changed later
  35130. using the setName() and setButtonText() methods)
  35131. @param toolTip an optional string to use as a toolip
  35132. @see Button
  35133. */
  35134. TextButton (const String& buttonName = String::empty,
  35135. const String& toolTip = String::empty);
  35136. /** Destructor. */
  35137. ~TextButton();
  35138. /** A set of colour IDs to use to change the colour of various aspects of the button.
  35139. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35140. methods.
  35141. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35142. */
  35143. enum ColourIds
  35144. {
  35145. buttonColourId = 0x1000100, /**< The colour used to fill the button shape (when the button is toggled
  35146. 'off'). The look-and-feel class might re-interpret this to add
  35147. effects, etc. */
  35148. buttonOnColourId = 0x1000101, /**< The colour used to fill the button shape (when the button is toggled
  35149. 'on'). The look-and-feel class might re-interpret this to add
  35150. effects, etc. */
  35151. textColourOffId = 0x1000102, /**< The colour to use for the button's text when the button's toggle state is "off". */
  35152. textColourOnId = 0x1000103 /**< The colour to use for the button's text.when the button's toggle state is "on". */
  35153. };
  35154. /** Resizes the button to fit neatly around its current text.
  35155. If newHeight is >= 0, the button's height will be changed to this
  35156. value. If it's less than zero, its height will be unaffected.
  35157. */
  35158. void changeWidthToFitText (int newHeight = -1);
  35159. /** This can be overridden to use different fonts than the default one.
  35160. Note that you'll need to set the font's size appropriately, too.
  35161. */
  35162. virtual const Font getFont();
  35163. protected:
  35164. /** @internal */
  35165. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  35166. /** @internal */
  35167. void colourChanged();
  35168. private:
  35169. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextButton);
  35170. };
  35171. #endif // __JUCE_TEXTBUTTON_JUCEHEADER__
  35172. /*** End of inlined file: juce_TextButton.h ***/
  35173. /**
  35174. A component displaying a list of plugins, with options to scan for them,
  35175. add, remove and sort them.
  35176. */
  35177. class JUCE_API PluginListComponent : public Component,
  35178. public ListBoxModel,
  35179. public ChangeListener,
  35180. public ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  35181. public Timer
  35182. {
  35183. public:
  35184. /**
  35185. Creates the list component.
  35186. For info about the deadMansPedalFile, see the PluginDirectoryScanner constructor.
  35187. The properties file, if supplied, is used to store the user's last search paths.
  35188. */
  35189. PluginListComponent (KnownPluginList& listToRepresent,
  35190. const File& deadMansPedalFile,
  35191. PropertiesFile* propertiesToUse);
  35192. /** Destructor. */
  35193. ~PluginListComponent();
  35194. /** @internal */
  35195. void resized();
  35196. /** @internal */
  35197. bool isInterestedInFileDrag (const StringArray& files);
  35198. /** @internal */
  35199. void filesDropped (const StringArray& files, int, int);
  35200. /** @internal */
  35201. int getNumRows();
  35202. /** @internal */
  35203. void paintListBoxItem (int row, Graphics& g, int width, int height, bool rowIsSelected);
  35204. /** @internal */
  35205. void deleteKeyPressed (int lastRowSelected);
  35206. /** @internal */
  35207. void buttonClicked (Button* b);
  35208. /** @internal */
  35209. void changeListenerCallback (ChangeBroadcaster*);
  35210. /** @internal */
  35211. void timerCallback();
  35212. private:
  35213. KnownPluginList& list;
  35214. File deadMansPedalFile;
  35215. ListBox listBox;
  35216. TextButton optionsButton;
  35217. PropertiesFile* propertiesToUse;
  35218. int typeToScan;
  35219. void scanFor (AudioPluginFormat* format);
  35220. static void optionsMenuStaticCallback (int result, PluginListComponent*);
  35221. void optionsMenuCallback (int result);
  35222. void updateList();
  35223. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PluginListComponent);
  35224. };
  35225. #endif // __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  35226. /*** End of inlined file: juce_PluginListComponent.h ***/
  35227. #endif
  35228. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  35229. #endif
  35230. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  35231. #endif
  35232. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  35233. #endif
  35234. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  35235. /*** Start of inlined file: juce_AudioProcessorGraph.h ***/
  35236. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  35237. #define __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  35238. /**
  35239. A type of AudioProcessor which plays back a graph of other AudioProcessors.
  35240. Use one of these objects if you want to wire-up a set of AudioProcessors
  35241. and play back the result.
  35242. Processors can be added to the graph as "nodes" using addNode(), and once
  35243. added, you can connect any of their input or output channels to other
  35244. nodes using addConnection().
  35245. To play back a graph through an audio device, you might want to use an
  35246. AudioProcessorPlayer object.
  35247. */
  35248. class JUCE_API AudioProcessorGraph : public AudioProcessor,
  35249. public AsyncUpdater
  35250. {
  35251. public:
  35252. /** Creates an empty graph.
  35253. */
  35254. AudioProcessorGraph();
  35255. /** Destructor.
  35256. Any processor objects that have been added to the graph will also be deleted.
  35257. */
  35258. ~AudioProcessorGraph();
  35259. /** Represents one of the nodes, or processors, in an AudioProcessorGraph.
  35260. To create a node, call AudioProcessorGraph::addNode().
  35261. */
  35262. class JUCE_API Node : public ReferenceCountedObject
  35263. {
  35264. public:
  35265. /** The ID number assigned to this node.
  35266. This is assigned by the graph that owns it, and can't be changed.
  35267. */
  35268. const uint32 nodeId;
  35269. /** The actual processor object that this node represents. */
  35270. AudioProcessor* getProcessor() const noexcept { return processor; }
  35271. /** A set of user-definable properties that are associated with this node.
  35272. This can be used to attach values to the node for whatever purpose seems
  35273. useful. For example, you might store an x and y position if your application
  35274. is displaying the nodes on-screen.
  35275. */
  35276. NamedValueSet properties;
  35277. /** A convenient typedef for referring to a pointer to a node object.
  35278. */
  35279. typedef ReferenceCountedObjectPtr <Node> Ptr;
  35280. private:
  35281. friend class AudioProcessorGraph;
  35282. const ScopedPointer<AudioProcessor> processor;
  35283. bool isPrepared;
  35284. Node (uint32 nodeId, AudioProcessor* processor) noexcept;
  35285. void prepare (double sampleRate, int blockSize, AudioProcessorGraph* graph);
  35286. void unprepare();
  35287. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Node);
  35288. };
  35289. /** Represents a connection between two channels of two nodes in an AudioProcessorGraph.
  35290. To create a connection, use AudioProcessorGraph::addConnection().
  35291. */
  35292. struct JUCE_API Connection
  35293. {
  35294. public:
  35295. Connection (uint32 sourceNodeId, int sourceChannelIndex,
  35296. uint32 destNodeId, int destChannelIndex) noexcept;
  35297. /** The ID number of the node which is the input source for this connection.
  35298. @see AudioProcessorGraph::getNodeForId
  35299. */
  35300. uint32 sourceNodeId;
  35301. /** The index of the output channel of the source node from which this
  35302. connection takes its data.
  35303. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  35304. it is referring to the source node's midi output. Otherwise, it is the zero-based
  35305. index of an audio output channel in the source node.
  35306. */
  35307. int sourceChannelIndex;
  35308. /** The ID number of the node which is the destination for this connection.
  35309. @see AudioProcessorGraph::getNodeForId
  35310. */
  35311. uint32 destNodeId;
  35312. /** The index of the input channel of the destination node to which this
  35313. connection delivers its data.
  35314. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  35315. it is referring to the destination node's midi input. Otherwise, it is the zero-based
  35316. index of an audio input channel in the destination node.
  35317. */
  35318. int destChannelIndex;
  35319. private:
  35320. JUCE_LEAK_DETECTOR (Connection);
  35321. };
  35322. /** Deletes all nodes and connections from this graph.
  35323. Any processor objects in the graph will be deleted.
  35324. */
  35325. void clear();
  35326. /** Returns the number of nodes in the graph. */
  35327. int getNumNodes() const { return nodes.size(); }
  35328. /** Returns a pointer to one of the nodes in the graph.
  35329. This will return 0 if the index is out of range.
  35330. @see getNodeForId
  35331. */
  35332. Node* getNode (const int index) const { return nodes [index]; }
  35333. /** Searches the graph for a node with the given ID number and returns it.
  35334. If no such node was found, this returns 0.
  35335. @see getNode
  35336. */
  35337. Node* getNodeForId (const uint32 nodeId) const;
  35338. /** Adds a node to the graph.
  35339. This creates a new node in the graph, for the specified processor. Once you have
  35340. added a processor to the graph, the graph owns it and will delete it later when
  35341. it is no longer needed.
  35342. The optional nodeId parameter lets you specify an ID to use for the node, but
  35343. if the value is already in use, this new node will overwrite the old one.
  35344. If this succeeds, it returns a pointer to the newly-created node.
  35345. */
  35346. Node* addNode (AudioProcessor* newProcessor, uint32 nodeId = 0);
  35347. /** Deletes a node within the graph which has the specified ID.
  35348. This will also delete any connections that are attached to this node.
  35349. */
  35350. bool removeNode (uint32 nodeId);
  35351. /** Returns the number of connections in the graph. */
  35352. int getNumConnections() const { return connections.size(); }
  35353. /** Returns a pointer to one of the connections in the graph. */
  35354. const Connection* getConnection (int index) const { return connections [index]; }
  35355. /** Searches for a connection between some specified channels.
  35356. If no such connection is found, this returns 0.
  35357. */
  35358. const Connection* getConnectionBetween (uint32 sourceNodeId,
  35359. int sourceChannelIndex,
  35360. uint32 destNodeId,
  35361. int destChannelIndex) const;
  35362. /** Returns true if there is a connection between any of the channels of
  35363. two specified nodes.
  35364. */
  35365. bool isConnected (uint32 possibleSourceNodeId,
  35366. uint32 possibleDestNodeId) const;
  35367. /** Returns true if it would be legal to connect the specified points.
  35368. */
  35369. bool canConnect (uint32 sourceNodeId, int sourceChannelIndex,
  35370. uint32 destNodeId, int destChannelIndex) const;
  35371. /** Attempts to connect two specified channels of two nodes.
  35372. If this isn't allowed (e.g. because you're trying to connect a midi channel
  35373. to an audio one or other such nonsense), then it'll return false.
  35374. */
  35375. bool addConnection (uint32 sourceNodeId, int sourceChannelIndex,
  35376. uint32 destNodeId, int destChannelIndex);
  35377. /** Deletes the connection with the specified index.
  35378. Returns true if a connection was actually deleted.
  35379. */
  35380. void removeConnection (int index);
  35381. /** Deletes any connection between two specified points.
  35382. Returns true if a connection was actually deleted.
  35383. */
  35384. bool removeConnection (uint32 sourceNodeId, int sourceChannelIndex,
  35385. uint32 destNodeId, int destChannelIndex);
  35386. /** Removes all connections from the specified node.
  35387. */
  35388. bool disconnectNode (uint32 nodeId);
  35389. /** Performs a sanity checks of all the connections.
  35390. This might be useful if some of the processors are doing things like changing
  35391. their channel counts, which could render some connections obsolete.
  35392. */
  35393. bool removeIllegalConnections();
  35394. /** A special number that represents the midi channel of a node.
  35395. This is used as a channel index value if you want to refer to the midi input
  35396. or output instead of an audio channel.
  35397. */
  35398. static const int midiChannelIndex;
  35399. /** A special type of AudioProcessor that can live inside an AudioProcessorGraph
  35400. in order to use the audio that comes into and out of the graph itself.
  35401. If you create an AudioGraphIOProcessor in "input" mode, it will act as a
  35402. node in the graph which delivers the audio that is coming into the parent
  35403. graph. This allows you to stream the data to other nodes and process the
  35404. incoming audio.
  35405. Likewise, one of these in "output" mode can be sent data which it will add to
  35406. the sum of data being sent to the graph's output.
  35407. @see AudioProcessorGraph
  35408. */
  35409. class JUCE_API AudioGraphIOProcessor : public AudioPluginInstance
  35410. {
  35411. public:
  35412. /** Specifies the mode in which this processor will operate.
  35413. */
  35414. enum IODeviceType
  35415. {
  35416. audioInputNode, /**< In this mode, the processor has output channels
  35417. representing all the audio input channels that are
  35418. coming into its parent audio graph. */
  35419. audioOutputNode, /**< In this mode, the processor has input channels
  35420. representing all the audio output channels that are
  35421. going out of its parent audio graph. */
  35422. midiInputNode, /**< In this mode, the processor has a midi output which
  35423. delivers the same midi data that is arriving at its
  35424. parent graph. */
  35425. midiOutputNode /**< In this mode, the processor has a midi input and
  35426. any data sent to it will be passed out of the parent
  35427. graph. */
  35428. };
  35429. /** Returns the mode of this processor. */
  35430. IODeviceType getType() const { return type; }
  35431. /** Returns the parent graph to which this processor belongs, or 0 if it
  35432. hasn't yet been added to one. */
  35433. AudioProcessorGraph* getParentGraph() const { return graph; }
  35434. /** True if this is an audio or midi input. */
  35435. bool isInput() const;
  35436. /** True if this is an audio or midi output. */
  35437. bool isOutput() const;
  35438. AudioGraphIOProcessor (const IODeviceType type);
  35439. ~AudioGraphIOProcessor();
  35440. const String getName() const;
  35441. void fillInPluginDescription (PluginDescription& d) const;
  35442. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  35443. void releaseResources();
  35444. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  35445. const String getInputChannelName (int channelIndex) const;
  35446. const String getOutputChannelName (int channelIndex) const;
  35447. bool isInputChannelStereoPair (int index) const;
  35448. bool isOutputChannelStereoPair (int index) const;
  35449. bool acceptsMidi() const;
  35450. bool producesMidi() const;
  35451. bool hasEditor() const;
  35452. AudioProcessorEditor* createEditor();
  35453. int getNumParameters();
  35454. const String getParameterName (int);
  35455. float getParameter (int);
  35456. const String getParameterText (int);
  35457. void setParameter (int, float);
  35458. int getNumPrograms();
  35459. int getCurrentProgram();
  35460. void setCurrentProgram (int);
  35461. const String getProgramName (int);
  35462. void changeProgramName (int, const String&);
  35463. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  35464. void setStateInformation (const void* data, int sizeInBytes);
  35465. /** @internal */
  35466. void setParentGraph (AudioProcessorGraph* graph);
  35467. private:
  35468. const IODeviceType type;
  35469. AudioProcessorGraph* graph;
  35470. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioGraphIOProcessor);
  35471. };
  35472. // AudioProcessor methods:
  35473. const String getName() const;
  35474. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  35475. void releaseResources();
  35476. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  35477. const String getInputChannelName (int channelIndex) const;
  35478. const String getOutputChannelName (int channelIndex) const;
  35479. bool isInputChannelStereoPair (int index) const;
  35480. bool isOutputChannelStereoPair (int index) const;
  35481. bool acceptsMidi() const;
  35482. bool producesMidi() const;
  35483. bool hasEditor() const { return false; }
  35484. AudioProcessorEditor* createEditor() { return nullptr; }
  35485. int getNumParameters() { return 0; }
  35486. const String getParameterName (int) { return String::empty; }
  35487. float getParameter (int) { return 0; }
  35488. const String getParameterText (int) { return String::empty; }
  35489. void setParameter (int, float) { }
  35490. int getNumPrograms() { return 0; }
  35491. int getCurrentProgram() { return 0; }
  35492. void setCurrentProgram (int) { }
  35493. const String getProgramName (int) { return String::empty; }
  35494. void changeProgramName (int, const String&) { }
  35495. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  35496. void setStateInformation (const void* data, int sizeInBytes);
  35497. /** @internal */
  35498. void handleAsyncUpdate();
  35499. private:
  35500. ReferenceCountedArray <Node> nodes;
  35501. OwnedArray <Connection> connections;
  35502. uint32 lastNodeId;
  35503. AudioSampleBuffer renderingBuffers;
  35504. OwnedArray <MidiBuffer> midiBuffers;
  35505. CriticalSection renderLock;
  35506. Array<void*> renderingOps;
  35507. friend class AudioGraphIOProcessor;
  35508. AudioSampleBuffer* currentAudioInputBuffer;
  35509. AudioSampleBuffer currentAudioOutputBuffer;
  35510. MidiBuffer* currentMidiInputBuffer;
  35511. MidiBuffer currentMidiOutputBuffer;
  35512. void clearRenderingSequence();
  35513. void buildRenderingSequence();
  35514. bool isAnInputTo (uint32 possibleInputId, uint32 possibleDestinationId, int recursionCheck) const;
  35515. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessorGraph);
  35516. };
  35517. #endif // __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  35518. /*** End of inlined file: juce_AudioProcessorGraph.h ***/
  35519. #endif
  35520. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  35521. #endif
  35522. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  35523. /*** Start of inlined file: juce_AudioProcessorPlayer.h ***/
  35524. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  35525. #define __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  35526. /**
  35527. An AudioIODeviceCallback object which streams audio through an AudioProcessor.
  35528. To use one of these, just make it the callback used by your AudioIODevice, and
  35529. give it a processor to use by calling setProcessor().
  35530. It's also a MidiInputCallback, so you can connect it to both an audio and midi
  35531. input to send both streams through the processor.
  35532. @see AudioProcessor, AudioProcessorGraph
  35533. */
  35534. class JUCE_API AudioProcessorPlayer : public AudioIODeviceCallback,
  35535. public MidiInputCallback
  35536. {
  35537. public:
  35538. /**
  35539. */
  35540. AudioProcessorPlayer();
  35541. /** Destructor. */
  35542. virtual ~AudioProcessorPlayer();
  35543. /** Sets the processor that should be played.
  35544. The processor that is passed in will not be deleted or owned by this object.
  35545. To stop anything playing, pass in 0 to this method.
  35546. */
  35547. void setProcessor (AudioProcessor* processorToPlay);
  35548. /** Returns the current audio processor that is being played.
  35549. */
  35550. AudioProcessor* getCurrentProcessor() const { return processor; }
  35551. /** Returns a midi message collector that you can pass midi messages to if you
  35552. want them to be injected into the midi stream that is being sent to the
  35553. processor.
  35554. */
  35555. MidiMessageCollector& getMidiMessageCollector() { return messageCollector; }
  35556. /** @internal */
  35557. void audioDeviceIOCallback (const float** inputChannelData,
  35558. int totalNumInputChannels,
  35559. float** outputChannelData,
  35560. int totalNumOutputChannels,
  35561. int numSamples);
  35562. /** @internal */
  35563. void audioDeviceAboutToStart (AudioIODevice* device);
  35564. /** @internal */
  35565. void audioDeviceStopped();
  35566. /** @internal */
  35567. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  35568. private:
  35569. AudioProcessor* processor;
  35570. CriticalSection lock;
  35571. double sampleRate;
  35572. int blockSize;
  35573. bool isPrepared;
  35574. int numInputChans, numOutputChans;
  35575. float* channels [128];
  35576. AudioSampleBuffer tempBuffer;
  35577. MidiBuffer incomingMidi;
  35578. MidiMessageCollector messageCollector;
  35579. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessorPlayer);
  35580. };
  35581. #endif // __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  35582. /*** End of inlined file: juce_AudioProcessorPlayer.h ***/
  35583. #endif
  35584. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  35585. /*** Start of inlined file: juce_GenericAudioProcessorEditor.h ***/
  35586. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  35587. #define __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  35588. /*** Start of inlined file: juce_PropertyPanel.h ***/
  35589. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  35590. #define __JUCE_PROPERTYPANEL_JUCEHEADER__
  35591. /*** Start of inlined file: juce_PropertyComponent.h ***/
  35592. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  35593. #define __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  35594. class EditableProperty;
  35595. /**
  35596. A base class for a component that goes in a PropertyPanel and displays one of
  35597. an item's properties.
  35598. Subclasses of this are used to display a property in various forms, e.g. a
  35599. ChoicePropertyComponent shows its value as a combo box; a SliderPropertyComponent
  35600. shows its value as a slider; a TextPropertyComponent as a text box, etc.
  35601. A subclass must implement the refresh() method which will be called to tell the
  35602. component to update itself, and is also responsible for calling this it when the
  35603. item that it refers to is changed.
  35604. @see PropertyPanel, TextPropertyComponent, SliderPropertyComponent,
  35605. ChoicePropertyComponent, ButtonPropertyComponent, BooleanPropertyComponent
  35606. */
  35607. class JUCE_API PropertyComponent : public Component,
  35608. public SettableTooltipClient
  35609. {
  35610. public:
  35611. /** Creates a PropertyComponent.
  35612. @param propertyName the name is stored as this component's name, and is
  35613. used as the name displayed next to this component in
  35614. a property panel
  35615. @param preferredHeight the height that the component should be given - some
  35616. items may need to be larger than a normal row height.
  35617. This value can also be set if a subclass changes the
  35618. preferredHeight member variable.
  35619. */
  35620. PropertyComponent (const String& propertyName,
  35621. int preferredHeight = 25);
  35622. /** Destructor. */
  35623. ~PropertyComponent();
  35624. /** Returns this item's preferred height.
  35625. This value is specified either in the constructor or by a subclass changing the
  35626. preferredHeight member variable.
  35627. */
  35628. int getPreferredHeight() const noexcept { return preferredHeight; }
  35629. void setPreferredHeight (int newHeight) noexcept { preferredHeight = newHeight; }
  35630. /** Updates the property component if the item it refers to has changed.
  35631. A subclass must implement this method, and other objects may call it to
  35632. force it to refresh itself.
  35633. The subclass should be economical in the amount of work is done, so for
  35634. example it should check whether it really needs to do a repaint rather than
  35635. just doing one every time this method is called, as it may be called when
  35636. the value being displayed hasn't actually changed.
  35637. */
  35638. virtual void refresh() = 0;
  35639. /** The default paint method fills the background and draws a label for the
  35640. item's name.
  35641. @see LookAndFeel::drawPropertyComponentBackground(), LookAndFeel::drawPropertyComponentLabel()
  35642. */
  35643. void paint (Graphics& g);
  35644. /** The default resize method positions any child component to the right of this
  35645. one, based on the look and feel's default label size.
  35646. */
  35647. void resized();
  35648. /** By default, this just repaints the component. */
  35649. void enablementChanged();
  35650. protected:
  35651. /** Used by the PropertyPanel to determine how high this component needs to be.
  35652. A subclass can update this value in its constructor but shouldn't alter it later
  35653. as changes won't necessarily be picked up.
  35654. */
  35655. int preferredHeight;
  35656. private:
  35657. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PropertyComponent);
  35658. };
  35659. #endif // __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  35660. /*** End of inlined file: juce_PropertyComponent.h ***/
  35661. /**
  35662. A panel that holds a list of PropertyComponent objects.
  35663. This panel displays a list of PropertyComponents, and allows them to be organised
  35664. into collapsible sections.
  35665. To use, simply create one of these and add your properties to it with addProperties()
  35666. or addSection().
  35667. @see PropertyComponent
  35668. */
  35669. class JUCE_API PropertyPanel : public Component
  35670. {
  35671. public:
  35672. /** Creates an empty property panel. */
  35673. PropertyPanel();
  35674. /** Destructor. */
  35675. ~PropertyPanel();
  35676. /** Deletes all property components from the panel.
  35677. */
  35678. void clear();
  35679. /** Adds a set of properties to the panel.
  35680. The components in the list will be owned by this object and will be automatically
  35681. deleted later on when no longer needed.
  35682. These properties are added without them being inside a named section. If you
  35683. want them to be kept together in a collapsible section, use addSection() instead.
  35684. */
  35685. void addProperties (const Array <PropertyComponent*>& newPropertyComponents);
  35686. /** Adds a set of properties to the panel.
  35687. These properties are added at the bottom of the list, under a section heading with
  35688. a plus/minus button that allows it to be opened and closed.
  35689. The components in the list will be owned by this object and will be automatically
  35690. deleted later on when no longer needed.
  35691. To add properies without them being in a section, use addProperties().
  35692. */
  35693. void addSection (const String& sectionTitle,
  35694. const Array <PropertyComponent*>& newPropertyComponents,
  35695. bool shouldSectionInitiallyBeOpen = true);
  35696. /** Calls the refresh() method of all PropertyComponents in the panel */
  35697. void refreshAll() const;
  35698. /** Returns a list of all the names of sections in the panel.
  35699. These are the sections that have been added with addSection().
  35700. */
  35701. StringArray getSectionNames() const;
  35702. /** Returns true if the section at this index is currently open.
  35703. The index is from 0 up to the number of items returned by getSectionNames().
  35704. */
  35705. bool isSectionOpen (int sectionIndex) const;
  35706. /** Opens or closes one of the sections.
  35707. The index is from 0 up to the number of items returned by getSectionNames().
  35708. */
  35709. void setSectionOpen (int sectionIndex, bool shouldBeOpen);
  35710. /** Enables or disables one of the sections.
  35711. The index is from 0 up to the number of items returned by getSectionNames().
  35712. */
  35713. void setSectionEnabled (int sectionIndex, bool shouldBeEnabled);
  35714. /** Saves the current state of open/closed sections so it can be restored later.
  35715. The caller is responsible for deleting the object that is returned.
  35716. To restore this state, use restoreOpennessState().
  35717. @see restoreOpennessState
  35718. */
  35719. XmlElement* getOpennessState() const;
  35720. /** Restores a previously saved arrangement of open/closed sections.
  35721. This will try to restore a snapshot of the panel's state that was created by
  35722. the getOpennessState() method. If any of the sections named in the original
  35723. XML aren't present, they will be ignored.
  35724. @see getOpennessState
  35725. */
  35726. void restoreOpennessState (const XmlElement& newState);
  35727. /** Sets a message to be displayed when there are no properties in the panel.
  35728. The default message is "nothing selected".
  35729. */
  35730. void setMessageWhenEmpty (const String& newMessage);
  35731. /** Returns the message that is displayed when there are no properties.
  35732. @see setMessageWhenEmpty
  35733. */
  35734. const String& getMessageWhenEmpty() const;
  35735. /** @internal */
  35736. void paint (Graphics& g);
  35737. /** @internal */
  35738. void resized();
  35739. private:
  35740. Viewport viewport;
  35741. class PropertyHolderComponent;
  35742. PropertyHolderComponent* propertyHolderComponent;
  35743. String messageWhenEmpty;
  35744. void updatePropHolderLayout() const;
  35745. void updatePropHolderLayout (int width) const;
  35746. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PropertyPanel);
  35747. };
  35748. #endif // __JUCE_PROPERTYPANEL_JUCEHEADER__
  35749. /*** End of inlined file: juce_PropertyPanel.h ***/
  35750. /**
  35751. A type of UI component that displays the parameters of an AudioProcessor as
  35752. a simple list of sliders.
  35753. This can be used for showing an editor for a processor that doesn't supply
  35754. its own custom editor.
  35755. @see AudioProcessor
  35756. */
  35757. class JUCE_API GenericAudioProcessorEditor : public AudioProcessorEditor
  35758. {
  35759. public:
  35760. GenericAudioProcessorEditor (AudioProcessor* owner);
  35761. ~GenericAudioProcessorEditor();
  35762. void paint (Graphics& g);
  35763. void resized();
  35764. private:
  35765. PropertyPanel panel;
  35766. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GenericAudioProcessorEditor);
  35767. };
  35768. #endif // __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  35769. /*** End of inlined file: juce_GenericAudioProcessorEditor.h ***/
  35770. #endif
  35771. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  35772. /*** Start of inlined file: juce_Sampler.h ***/
  35773. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  35774. #define __JUCE_SAMPLER_JUCEHEADER__
  35775. /*** Start of inlined file: juce_Synthesiser.h ***/
  35776. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  35777. #define __JUCE_SYNTHESISER_JUCEHEADER__
  35778. /**
  35779. Describes one of the sounds that a Synthesiser can play.
  35780. A synthesiser can contain one or more sounds, and a sound can choose which
  35781. midi notes and channels can trigger it.
  35782. The SynthesiserSound is a passive class that just describes what the sound is -
  35783. the actual audio rendering for a sound is done by a SynthesiserVoice. This allows
  35784. more than one SynthesiserVoice to play the same sound at the same time.
  35785. @see Synthesiser, SynthesiserVoice
  35786. */
  35787. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  35788. {
  35789. protected:
  35790. SynthesiserSound();
  35791. public:
  35792. /** Destructor. */
  35793. virtual ~SynthesiserSound();
  35794. /** Returns true if this sound should be played when a given midi note is pressed.
  35795. The Synthesiser will use this information when deciding which sounds to trigger
  35796. for a given note.
  35797. */
  35798. virtual bool appliesToNote (const int midiNoteNumber) = 0;
  35799. /** Returns true if the sound should be triggered by midi events on a given channel.
  35800. The Synthesiser will use this information when deciding which sounds to trigger
  35801. for a given note.
  35802. */
  35803. virtual bool appliesToChannel (const int midiChannel) = 0;
  35804. /**
  35805. */
  35806. typedef ReferenceCountedObjectPtr <SynthesiserSound> Ptr;
  35807. private:
  35808. JUCE_LEAK_DETECTOR (SynthesiserSound);
  35809. };
  35810. /**
  35811. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  35812. A voice plays a single sound at a time, and a synthesiser holds an array of
  35813. voices so that it can play polyphonically.
  35814. @see Synthesiser, SynthesiserSound
  35815. */
  35816. class JUCE_API SynthesiserVoice
  35817. {
  35818. public:
  35819. /** Creates a voice. */
  35820. SynthesiserVoice();
  35821. /** Destructor. */
  35822. virtual ~SynthesiserVoice();
  35823. /** Returns the midi note that this voice is currently playing.
  35824. Returns a value less than 0 if no note is playing.
  35825. */
  35826. int getCurrentlyPlayingNote() const { return currentlyPlayingNote; }
  35827. /** Returns the sound that this voice is currently playing.
  35828. Returns 0 if it's not playing.
  35829. */
  35830. SynthesiserSound::Ptr getCurrentlyPlayingSound() const { return currentlyPlayingSound; }
  35831. /** Must return true if this voice object is capable of playing the given sound.
  35832. If there are different classes of sound, and different classes of voice, a voice can
  35833. choose which ones it wants to take on.
  35834. A typical implementation of this method may just return true if there's only one type
  35835. of voice and sound, or it might check the type of the sound object passed-in and
  35836. see if it's one that it understands.
  35837. */
  35838. virtual bool canPlaySound (SynthesiserSound* sound) = 0;
  35839. /** Called to start a new note.
  35840. This will be called during the rendering callback, so must be fast and thread-safe.
  35841. */
  35842. virtual void startNote (const int midiNoteNumber,
  35843. const float velocity,
  35844. SynthesiserSound* sound,
  35845. const int currentPitchWheelPosition) = 0;
  35846. /** Called to stop a note.
  35847. This will be called during the rendering callback, so must be fast and thread-safe.
  35848. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  35849. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  35850. and allow the synth to reassign it another sound.
  35851. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  35852. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  35853. finishes playing (during the rendering callback), it must make sure that it calls
  35854. clearCurrentNote().
  35855. */
  35856. virtual void stopNote (const bool allowTailOff) = 0;
  35857. /** Called to let the voice know that the pitch wheel has been moved.
  35858. This will be called during the rendering callback, so must be fast and thread-safe.
  35859. */
  35860. virtual void pitchWheelMoved (const int newValue) = 0;
  35861. /** Called to let the voice know that a midi controller has been moved.
  35862. This will be called during the rendering callback, so must be fast and thread-safe.
  35863. */
  35864. virtual void controllerMoved (const int controllerNumber,
  35865. const int newValue) = 0;
  35866. /** Renders the next block of data for this voice.
  35867. The output audio data must be added to the current contents of the buffer provided.
  35868. Only the region of the buffer between startSample and (startSample + numSamples)
  35869. should be altered by this method.
  35870. If the voice is currently silent, it should just return without doing anything.
  35871. If the sound that the voice is playing finishes during the course of this rendered
  35872. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  35873. The size of the blocks that are rendered can change each time it is called, and may
  35874. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  35875. the voice's methods will be called to tell it about note and controller events.
  35876. */
  35877. virtual void renderNextBlock (AudioSampleBuffer& outputBuffer,
  35878. int startSample,
  35879. int numSamples) = 0;
  35880. /** Returns true if the voice is currently playing a sound which is mapped to the given
  35881. midi channel.
  35882. If it's not currently playing, this will return false.
  35883. */
  35884. bool isPlayingChannel (int midiChannel) const;
  35885. /** Changes the voice's reference sample rate.
  35886. The rate is set so that subclasses know the output rate and can set their pitch
  35887. accordingly.
  35888. This method is called by the synth, and subclasses can access the current rate with
  35889. the currentSampleRate member.
  35890. */
  35891. void setCurrentPlaybackSampleRate (double newRate);
  35892. protected:
  35893. /** Returns the current target sample rate at which rendering is being done.
  35894. This is available for subclasses so they can pitch things correctly.
  35895. */
  35896. double getSampleRate() const { return currentSampleRate; }
  35897. /** Resets the state of this voice after a sound has finished playing.
  35898. The subclass must call this when it finishes playing a note and becomes available
  35899. to play new ones.
  35900. It must either call it in the stopNote() method, or if the voice is tailing off,
  35901. then it should call it later during the renderNextBlock method, as soon as it
  35902. finishes its tail-off.
  35903. It can also be called at any time during the render callback if the sound happens
  35904. to have finished, e.g. if it's playing a sample and the sample finishes.
  35905. */
  35906. void clearCurrentNote();
  35907. private:
  35908. friend class Synthesiser;
  35909. double currentSampleRate;
  35910. int currentlyPlayingNote;
  35911. uint32 noteOnTime;
  35912. SynthesiserSound::Ptr currentlyPlayingSound;
  35913. bool keyIsDown; // the voice may still be playing when the key is not down (i.e. sustain pedal)
  35914. bool sostenutoPedalDown;
  35915. JUCE_LEAK_DETECTOR (SynthesiserVoice);
  35916. };
  35917. /**
  35918. Base class for a musical device that can play sounds.
  35919. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  35920. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  35921. which can play back one of these sounds.
  35922. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  35923. set of sounds, and a set of voices it can use to play them. If you only give it
  35924. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  35925. have available.
  35926. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  35927. events that go in will be scanned for note on/off messages, and these are used to
  35928. start and stop the voices playing the appropriate sounds.
  35929. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  35930. noteOff() and other controller methods.
  35931. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  35932. what the target playback rate is. This value is passed on to the voices so that
  35933. they can pitch their output correctly.
  35934. */
  35935. class JUCE_API Synthesiser
  35936. {
  35937. public:
  35938. /** Creates a new synthesiser.
  35939. You'll need to add some sounds and voices before it'll make any sound..
  35940. */
  35941. Synthesiser();
  35942. /** Destructor. */
  35943. virtual ~Synthesiser();
  35944. /** Deletes all voices. */
  35945. void clearVoices();
  35946. /** Returns the number of voices that have been added. */
  35947. int getNumVoices() const { return voices.size(); }
  35948. /** Returns one of the voices that have been added. */
  35949. SynthesiserVoice* getVoice (int index) const;
  35950. /** Adds a new voice to the synth.
  35951. All the voices should be the same class of object and are treated equally.
  35952. The object passed in will be managed by the synthesiser, which will delete
  35953. it later on when no longer needed. The caller should not retain a pointer to the
  35954. voice.
  35955. */
  35956. void addVoice (SynthesiserVoice* newVoice);
  35957. /** Deletes one of the voices. */
  35958. void removeVoice (int index);
  35959. /** Deletes all sounds. */
  35960. void clearSounds();
  35961. /** Returns the number of sounds that have been added to the synth. */
  35962. int getNumSounds() const { return sounds.size(); }
  35963. /** Returns one of the sounds. */
  35964. SynthesiserSound* getSound (int index) const { return sounds [index]; }
  35965. /** Adds a new sound to the synthesiser.
  35966. The object passed in is reference counted, so will be deleted when it is removed
  35967. from the synthesiser, and when no voices are still using it.
  35968. */
  35969. void addSound (const SynthesiserSound::Ptr& newSound);
  35970. /** Removes and deletes one of the sounds. */
  35971. void removeSound (int index);
  35972. /** If set to true, then the synth will try to take over an existing voice if
  35973. it runs out and needs to play another note.
  35974. The value of this boolean is passed into findFreeVoice(), so the result will
  35975. depend on the implementation of this method.
  35976. */
  35977. void setNoteStealingEnabled (bool shouldStealNotes);
  35978. /** Returns true if note-stealing is enabled.
  35979. @see setNoteStealingEnabled
  35980. */
  35981. bool isNoteStealingEnabled() const { return shouldStealNotes; }
  35982. /** Triggers a note-on event.
  35983. The default method here will find all the sounds that want to be triggered by
  35984. this note/channel. For each sound, it'll try to find a free voice, and use the
  35985. voice to start playing the sound.
  35986. Subclasses might want to override this if they need a more complex algorithm.
  35987. This method will be called automatically according to the midi data passed into
  35988. renderNextBlock(), but may be called explicitly too.
  35989. The midiChannel parameter is the channel, between 1 and 16 inclusive.
  35990. */
  35991. virtual void noteOn (int midiChannel,
  35992. int midiNoteNumber,
  35993. float velocity);
  35994. /** Triggers a note-off event.
  35995. This will turn off any voices that are playing a sound for the given note/channel.
  35996. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  35997. (if they can do). If this is false, the notes will all be cut off immediately.
  35998. This method will be called automatically according to the midi data passed into
  35999. renderNextBlock(), but may be called explicitly too.
  36000. The midiChannel parameter is the channel, between 1 and 16 inclusive.
  36001. */
  36002. virtual void noteOff (int midiChannel,
  36003. int midiNoteNumber,
  36004. bool allowTailOff);
  36005. /** Turns off all notes.
  36006. This will turn off any voices that are playing a sound on the given midi channel.
  36007. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  36008. which channel they're playing. Otherwise it represents a valid midi channel, from
  36009. 1 to 16 inclusive.
  36010. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  36011. (if they can do). If this is false, the notes will all be cut off immediately.
  36012. This method will be called automatically according to the midi data passed into
  36013. renderNextBlock(), but may be called explicitly too.
  36014. */
  36015. virtual void allNotesOff (int midiChannel,
  36016. bool allowTailOff);
  36017. /** Sends a pitch-wheel message.
  36018. This will send a pitch-wheel message to any voices that are playing sounds on
  36019. the given midi channel.
  36020. This method will be called automatically according to the midi data passed into
  36021. renderNextBlock(), but may be called explicitly too.
  36022. @param midiChannel the midi channel, from 1 to 16 inclusive
  36023. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  36024. */
  36025. virtual void handlePitchWheel (int midiChannel,
  36026. int wheelValue);
  36027. /** Sends a midi controller message.
  36028. This will send a midi controller message to any voices that are playing sounds on
  36029. the given midi channel.
  36030. This method will be called automatically according to the midi data passed into
  36031. renderNextBlock(), but may be called explicitly too.
  36032. @param midiChannel the midi channel, from 1 to 16 inclusive
  36033. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  36034. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  36035. */
  36036. virtual void handleController (int midiChannel,
  36037. int controllerNumber,
  36038. int controllerValue);
  36039. virtual void handleSustainPedal (int midiChannel, bool isDown);
  36040. virtual void handleSostenutoPedal (int midiChannel, bool isDown);
  36041. virtual void handleSoftPedal (int midiChannel, bool isDown);
  36042. /** Tells the synthesiser what the sample rate is for the audio it's being used to
  36043. render.
  36044. This value is propagated to the voices so that they can use it to render the correct
  36045. pitches.
  36046. */
  36047. void setCurrentPlaybackSampleRate (double sampleRate);
  36048. /** Creates the next block of audio output.
  36049. This will process the next numSamples of data from all the voices, and add that output
  36050. to the audio block supplied, starting from the offset specified. Note that the
  36051. data will be added to the current contents of the buffer, so you should clear it
  36052. before calling this method if necessary.
  36053. The midi events in the inputMidi buffer are parsed for note and controller events,
  36054. and these are used to trigger the voices. Note that the startSample offset applies
  36055. both to the audio output buffer and the midi input buffer, so any midi events
  36056. with timestamps outside the specified region will be ignored.
  36057. */
  36058. void renderNextBlock (AudioSampleBuffer& outputAudio,
  36059. const MidiBuffer& inputMidi,
  36060. int startSample,
  36061. int numSamples);
  36062. protected:
  36063. /** This is used to control access to the rendering callback and the note trigger methods. */
  36064. CriticalSection lock;
  36065. OwnedArray <SynthesiserVoice> voices;
  36066. ReferenceCountedArray <SynthesiserSound> sounds;
  36067. /** The last pitch-wheel values for each midi channel. */
  36068. int lastPitchWheelValues [16];
  36069. /** Searches through the voices to find one that's not currently playing, and which
  36070. can play the given sound.
  36071. Returns 0 if all voices are busy and stealing isn't enabled.
  36072. This can be overridden to implement custom voice-stealing algorithms.
  36073. */
  36074. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  36075. const bool stealIfNoneAvailable) const;
  36076. /** Starts a specified voice playing a particular sound.
  36077. You'll probably never need to call this, it's used internally by noteOn(), but
  36078. may be needed by subclasses for custom behaviours.
  36079. */
  36080. void startVoice (SynthesiserVoice* voice,
  36081. SynthesiserSound* sound,
  36082. int midiChannel,
  36083. int midiNoteNumber,
  36084. float velocity);
  36085. private:
  36086. double sampleRate;
  36087. uint32 lastNoteOnCounter;
  36088. bool shouldStealNotes;
  36089. BigInteger sustainPedalsDown;
  36090. void handleMidiEvent (const MidiMessage& m);
  36091. void stopVoice (SynthesiserVoice* voice, bool allowTailOff);
  36092. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  36093. // Note the new parameters for this method.
  36094. virtual int findFreeVoice (const bool) const { return 0; }
  36095. #endif
  36096. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Synthesiser);
  36097. };
  36098. #endif // __JUCE_SYNTHESISER_JUCEHEADER__
  36099. /*** End of inlined file: juce_Synthesiser.h ***/
  36100. /**
  36101. A subclass of SynthesiserSound that represents a sampled audio clip.
  36102. This is a pretty basic sampler, and just attempts to load the whole audio stream
  36103. into memory.
  36104. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  36105. give it some SampledSound objects to play.
  36106. @see SamplerVoice, Synthesiser, SynthesiserSound
  36107. */
  36108. class JUCE_API SamplerSound : public SynthesiserSound
  36109. {
  36110. public:
  36111. /** Creates a sampled sound from an audio reader.
  36112. This will attempt to load the audio from the source into memory and store
  36113. it in this object.
  36114. @param name a name for the sample
  36115. @param source the audio to load. This object can be safely deleted by the
  36116. caller after this constructor returns
  36117. @param midiNotes the set of midi keys that this sound should be played on. This
  36118. is used by the SynthesiserSound::appliesToNote() method
  36119. @param midiNoteForNormalPitch the midi note at which the sample should be played
  36120. with its natural rate. All other notes will be pitched
  36121. up or down relative to this one
  36122. @param attackTimeSecs the attack (fade-in) time, in seconds
  36123. @param releaseTimeSecs the decay (fade-out) time, in seconds
  36124. @param maxSampleLengthSeconds a maximum length of audio to read from the audio
  36125. source, in seconds
  36126. */
  36127. SamplerSound (const String& name,
  36128. AudioFormatReader& source,
  36129. const BigInteger& midiNotes,
  36130. int midiNoteForNormalPitch,
  36131. double attackTimeSecs,
  36132. double releaseTimeSecs,
  36133. double maxSampleLengthSeconds);
  36134. /** Destructor. */
  36135. ~SamplerSound();
  36136. /** Returns the sample's name */
  36137. const String& getName() const { return name; }
  36138. /** Returns the audio sample data.
  36139. This could be 0 if there was a problem loading it.
  36140. */
  36141. AudioSampleBuffer* getAudioData() const { return data; }
  36142. bool appliesToNote (const int midiNoteNumber);
  36143. bool appliesToChannel (const int midiChannel);
  36144. private:
  36145. friend class SamplerVoice;
  36146. String name;
  36147. ScopedPointer <AudioSampleBuffer> data;
  36148. double sourceSampleRate;
  36149. BigInteger midiNotes;
  36150. int length, attackSamples, releaseSamples;
  36151. int midiRootNote;
  36152. JUCE_LEAK_DETECTOR (SamplerSound);
  36153. };
  36154. /**
  36155. A subclass of SynthesiserVoice that can play a SamplerSound.
  36156. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  36157. give it some SampledSound objects to play.
  36158. @see SamplerSound, Synthesiser, SynthesiserVoice
  36159. */
  36160. class JUCE_API SamplerVoice : public SynthesiserVoice
  36161. {
  36162. public:
  36163. /** Creates a SamplerVoice.
  36164. */
  36165. SamplerVoice();
  36166. /** Destructor. */
  36167. ~SamplerVoice();
  36168. bool canPlaySound (SynthesiserSound* sound);
  36169. void startNote (const int midiNoteNumber,
  36170. const float velocity,
  36171. SynthesiserSound* sound,
  36172. const int currentPitchWheelPosition);
  36173. void stopNote (const bool allowTailOff);
  36174. void pitchWheelMoved (const int newValue);
  36175. void controllerMoved (const int controllerNumber,
  36176. const int newValue);
  36177. void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples);
  36178. private:
  36179. double pitchRatio;
  36180. double sourceSamplePosition;
  36181. float lgain, rgain, attackReleaseLevel, attackDelta, releaseDelta;
  36182. bool isInAttack, isInRelease;
  36183. JUCE_LEAK_DETECTOR (SamplerVoice);
  36184. };
  36185. #endif // __JUCE_SAMPLER_JUCEHEADER__
  36186. /*** End of inlined file: juce_Sampler.h ***/
  36187. #endif
  36188. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  36189. #endif
  36190. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36191. /*** Start of inlined file: juce_ActionBroadcaster.h ***/
  36192. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36193. #define __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36194. /** Manages a list of ActionListeners, and can send them messages.
  36195. To quickly add methods to your class that can add/remove action
  36196. listeners and broadcast to them, you can derive from this.
  36197. @see ActionListener, ChangeListener
  36198. */
  36199. class JUCE_API ActionBroadcaster
  36200. {
  36201. public:
  36202. /** Creates an ActionBroadcaster. */
  36203. ActionBroadcaster();
  36204. /** Destructor. */
  36205. virtual ~ActionBroadcaster();
  36206. /** Adds a listener to the list.
  36207. Trying to add a listener that's already on the list will have no effect.
  36208. */
  36209. void addActionListener (ActionListener* listener);
  36210. /** Removes a listener from the list.
  36211. If the listener isn't on the list, this won't have any effect.
  36212. */
  36213. void removeActionListener (ActionListener* listener);
  36214. /** Removes all listeners from the list. */
  36215. void removeAllActionListeners();
  36216. /** Broadcasts a message to all the registered listeners.
  36217. @see ActionListener::actionListenerCallback
  36218. */
  36219. void sendActionMessage (const String& message) const;
  36220. private:
  36221. class CallbackReceiver : public MessageListener
  36222. {
  36223. public:
  36224. CallbackReceiver();
  36225. void handleMessage (const Message&);
  36226. ActionBroadcaster* owner;
  36227. };
  36228. friend class CallbackReceiver;
  36229. CallbackReceiver callback;
  36230. SortedSet <ActionListener*> actionListeners;
  36231. CriticalSection actionListenerLock;
  36232. JUCE_DECLARE_NON_COPYABLE (ActionBroadcaster);
  36233. };
  36234. #endif // __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36235. /*** End of inlined file: juce_ActionBroadcaster.h ***/
  36236. #endif
  36237. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  36238. #endif
  36239. #ifndef __JUCE_APPLEREMOTE_JUCEHEADER__
  36240. /*** Start of inlined file: juce_AppleRemote.h ***/
  36241. #ifndef __JUCE_APPLEREMOTE_JUCEHEADER__
  36242. #define __JUCE_APPLEREMOTE_JUCEHEADER__
  36243. #if JUCE_MAC || DOXYGEN
  36244. /**
  36245. Receives events from an Apple IR remote control device (Only available in OSX!).
  36246. To use it, just create a subclass of this class, implementing the buttonPressed()
  36247. callback, then call start() and stop() to start or stop receiving events.
  36248. */
  36249. class JUCE_API AppleRemoteDevice
  36250. {
  36251. public:
  36252. AppleRemoteDevice();
  36253. virtual ~AppleRemoteDevice();
  36254. /** The set of buttons that may be pressed.
  36255. @see buttonPressed
  36256. */
  36257. enum ButtonType
  36258. {
  36259. menuButton = 0, /**< The menu button (if it's held for a short time). */
  36260. playButton, /**< The play button. */
  36261. plusButton, /**< The plus or volume-up button. */
  36262. minusButton, /**< The minus or volume-down button. */
  36263. rightButton, /**< The right button (if it's held for a short time). */
  36264. leftButton, /**< The left button (if it's held for a short time). */
  36265. rightButton_Long, /**< The right button (if it's held for a long time). */
  36266. leftButton_Long, /**< The menu button (if it's held for a long time). */
  36267. menuButton_Long, /**< The menu button (if it's held for a long time). */
  36268. playButtonSleepMode,
  36269. switched
  36270. };
  36271. /** Override this method to receive the callback about a button press.
  36272. The callback will happen on the application's message thread.
  36273. Some buttons trigger matching up and down events, in which the isDown parameter
  36274. will be true and then false. Others only send a single event when the
  36275. button is pressed.
  36276. */
  36277. virtual void buttonPressed (ButtonType buttonId, bool isDown) = 0;
  36278. /** Starts the device running and responding to events.
  36279. Returns true if it managed to open the device.
  36280. @param inExclusiveMode if true, the remote will be grabbed exclusively for this app,
  36281. and will not be available to any other part of the system. If
  36282. false, it will be shared with other apps.
  36283. @see stop
  36284. */
  36285. bool start (bool inExclusiveMode);
  36286. /** Stops the device running.
  36287. @see start
  36288. */
  36289. void stop();
  36290. /** Returns true if the device has been started successfully.
  36291. */
  36292. bool isActive() const;
  36293. /** Returns the ID number of the remote, if it has sent one.
  36294. */
  36295. int getRemoteId() const { return remoteId; }
  36296. /** @internal */
  36297. void handleCallbackInternal();
  36298. private:
  36299. void* device;
  36300. void* queue;
  36301. int remoteId;
  36302. bool open (bool openInExclusiveMode);
  36303. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AppleRemoteDevice);
  36304. };
  36305. #endif
  36306. #endif // __JUCE_APPLEREMOTE_JUCEHEADER__
  36307. /*** End of inlined file: juce_AppleRemote.h ***/
  36308. #endif
  36309. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  36310. #endif
  36311. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  36312. #endif
  36313. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  36314. #endif
  36315. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  36316. #endif
  36317. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  36318. /*** Start of inlined file: juce_InterprocessConnection.h ***/
  36319. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  36320. #define __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  36321. class InterprocessConnectionServer;
  36322. class MemoryBlock;
  36323. /**
  36324. Manages a simple two-way messaging connection to another process, using either
  36325. a socket or a named pipe as the transport medium.
  36326. To connect to a waiting socket or an open pipe, use the connectToSocket() or
  36327. connectToPipe() methods. If this succeeds, messages can be sent to the other end,
  36328. and incoming messages will result in a callback via the messageReceived()
  36329. method.
  36330. To open a pipe and wait for another client to connect to it, use the createPipe()
  36331. method.
  36332. To act as a socket server and create connections for one or more client, see the
  36333. InterprocessConnectionServer class.
  36334. @see InterprocessConnectionServer, Socket, NamedPipe
  36335. */
  36336. class JUCE_API InterprocessConnection : public Thread,
  36337. private MessageListener
  36338. {
  36339. public:
  36340. /** Creates a connection.
  36341. Connections are created manually, connecting them with the connectToSocket()
  36342. or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
  36343. when a client wants to connect.
  36344. @param callbacksOnMessageThread if true, callbacks to the connectionMade(),
  36345. connectionLost() and messageReceived() methods will
  36346. always be made using the message thread; if false,
  36347. these will be called immediately on the connection's
  36348. own thread.
  36349. @param magicMessageHeaderNumber a magic number to use in the header to check the
  36350. validity of the data blocks being sent and received. This
  36351. can be any number, but the sender and receiver must obviously
  36352. use matching values or they won't recognise each other.
  36353. */
  36354. InterprocessConnection (bool callbacksOnMessageThread = true,
  36355. uint32 magicMessageHeaderNumber = 0xf2b49e2c);
  36356. /** Destructor. */
  36357. ~InterprocessConnection();
  36358. /** Tries to connect this object to a socket.
  36359. For this to work, the machine on the other end needs to have a InterprocessConnectionServer
  36360. object waiting to receive client connections on this port number.
  36361. @param hostName the host computer, either a network address or name
  36362. @param portNumber the socket port number to try to connect to
  36363. @param timeOutMillisecs how long to keep trying before giving up
  36364. @returns true if the connection is established successfully
  36365. @see Socket
  36366. */
  36367. bool connectToSocket (const String& hostName,
  36368. int portNumber,
  36369. int timeOutMillisecs);
  36370. /** Tries to connect the object to an existing named pipe.
  36371. For this to work, another process on the same computer must already have opened
  36372. an InterprocessConnection object and used createPipe() to create a pipe for this
  36373. to connect to.
  36374. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  36375. @returns true if it connects successfully.
  36376. @see createPipe, NamedPipe
  36377. */
  36378. bool connectToPipe (const String& pipeName,
  36379. int pipeReceiveMessageTimeoutMs = -1);
  36380. /** Tries to create a new pipe for other processes to connect to.
  36381. This creates a pipe with the given name, so that other processes can use
  36382. connectToPipe() to connect to the other end.
  36383. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  36384. If another process is already using this pipe, this will fail and return false.
  36385. */
  36386. bool createPipe (const String& pipeName,
  36387. int pipeReceiveMessageTimeoutMs = -1);
  36388. /** Disconnects and closes any currently-open sockets or pipes. */
  36389. void disconnect();
  36390. /** True if a socket or pipe is currently active. */
  36391. bool isConnected() const;
  36392. /** Returns the socket that this connection is using (or null if it uses a pipe). */
  36393. StreamingSocket* getSocket() const noexcept { return socket; }
  36394. /** Returns the pipe that this connection is using (or null if it uses a socket). */
  36395. NamedPipe* getPipe() const noexcept { return pipe; }
  36396. /** Returns the name of the machine at the other end of this connection.
  36397. This will return an empty string if the other machine isn't known for
  36398. some reason.
  36399. */
  36400. String getConnectedHostName() const;
  36401. /** Tries to send a message to the other end of this connection.
  36402. This will fail if it's not connected, or if there's some kind of write error. If
  36403. it succeeds, the connection object at the other end will receive the message by
  36404. a callback to its messageReceived() method.
  36405. @see messageReceived
  36406. */
  36407. bool sendMessage (const MemoryBlock& message);
  36408. /** Called when the connection is first connected.
  36409. If the connection was created with the callbacksOnMessageThread flag set, then
  36410. this will be called on the message thread; otherwise it will be called on a server
  36411. thread.
  36412. */
  36413. virtual void connectionMade() = 0;
  36414. /** Called when the connection is broken.
  36415. If the connection was created with the callbacksOnMessageThread flag set, then
  36416. this will be called on the message thread; otherwise it will be called on a server
  36417. thread.
  36418. */
  36419. virtual void connectionLost() = 0;
  36420. /** Called when a message arrives.
  36421. When the object at the other end of this connection sends us a message with sendMessage(),
  36422. this callback is used to deliver it to us.
  36423. If the connection was created with the callbacksOnMessageThread flag set, then
  36424. this will be called on the message thread; otherwise it will be called on a server
  36425. thread.
  36426. @see sendMessage
  36427. */
  36428. virtual void messageReceived (const MemoryBlock& message) = 0;
  36429. private:
  36430. CriticalSection pipeAndSocketLock;
  36431. ScopedPointer <StreamingSocket> socket;
  36432. ScopedPointer <NamedPipe> pipe;
  36433. bool callbackConnectionState;
  36434. const bool useMessageThread;
  36435. const uint32 magicMessageHeader;
  36436. int pipeReceiveMessageTimeout;
  36437. friend class InterprocessConnectionServer;
  36438. void initialiseWithSocket (StreamingSocket* socket_);
  36439. void initialiseWithPipe (NamedPipe* pipe_);
  36440. void handleMessage (const Message& message);
  36441. void connectionMadeInt();
  36442. void connectionLostInt();
  36443. void deliverDataInt (const MemoryBlock& data);
  36444. bool readNextMessageInt();
  36445. void run();
  36446. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InterprocessConnection);
  36447. };
  36448. #endif // __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  36449. /*** End of inlined file: juce_InterprocessConnection.h ***/
  36450. #endif
  36451. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  36452. /*** Start of inlined file: juce_InterprocessConnectionServer.h ***/
  36453. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  36454. #define __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  36455. /**
  36456. An object that waits for client sockets to connect to a port on this host, and
  36457. creates InterprocessConnection objects for each one.
  36458. To use this, create a class derived from it which implements the createConnectionObject()
  36459. method, so that it creates suitable connection objects for each client that tries
  36460. to connect.
  36461. @see InterprocessConnection
  36462. */
  36463. class JUCE_API InterprocessConnectionServer : private Thread
  36464. {
  36465. public:
  36466. /** Creates an uninitialised server object.
  36467. */
  36468. InterprocessConnectionServer();
  36469. /** Destructor. */
  36470. ~InterprocessConnectionServer();
  36471. /** Starts an internal thread which listens on the given port number.
  36472. While this is running, in another process tries to connect with the
  36473. InterprocessConnection::connectToSocket() method, this object will call
  36474. createConnectionObject() to create a connection to that client.
  36475. Use stop() to stop the thread running.
  36476. @see createConnectionObject, stop
  36477. */
  36478. bool beginWaitingForSocket (int portNumber);
  36479. /** Terminates the listener thread, if it's active.
  36480. @see beginWaitingForSocket
  36481. */
  36482. void stop();
  36483. protected:
  36484. /** Creates a suitable connection object for a client process that wants to
  36485. connect to this one.
  36486. This will be called by the listener thread when a client process tries
  36487. to connect, and must return a new InterprocessConnection object that will
  36488. then run as this end of the connection.
  36489. @see InterprocessConnection
  36490. */
  36491. virtual InterprocessConnection* createConnectionObject() = 0;
  36492. private:
  36493. ScopedPointer <StreamingSocket> socket;
  36494. void run();
  36495. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InterprocessConnectionServer);
  36496. };
  36497. #endif // __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  36498. /*** End of inlined file: juce_InterprocessConnectionServer.h ***/
  36499. #endif
  36500. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  36501. #endif
  36502. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  36503. #endif
  36504. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  36505. #endif
  36506. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  36507. /*** Start of inlined file: juce_MessageManager.h ***/
  36508. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  36509. #define __JUCE_MESSAGEMANAGER_JUCEHEADER__
  36510. class Component;
  36511. class MessageManagerLock;
  36512. class ThreadPoolJob;
  36513. class ActionListener;
  36514. class ActionBroadcaster;
  36515. /** See MessageManager::callFunctionOnMessageThread() for use of this function type
  36516. */
  36517. typedef void* (MessageCallbackFunction) (void* userData);
  36518. /** Delivers Message objects to MessageListeners, and handles the event-dispatch loop.
  36519. @see Message, MessageListener, MessageManagerLock, JUCEApplication
  36520. */
  36521. class JUCE_API MessageManager
  36522. {
  36523. public:
  36524. /** Returns the global instance of the MessageManager. */
  36525. static MessageManager* getInstance() noexcept;
  36526. /** Runs the event dispatch loop until a stop message is posted.
  36527. This method is only intended to be run by the application's startup routine,
  36528. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  36529. @see stopDispatchLoop
  36530. */
  36531. void runDispatchLoop();
  36532. /** Sends a signal that the dispatch loop should terminate.
  36533. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  36534. will be interrupted and will return.
  36535. @see runDispatchLoop
  36536. */
  36537. void stopDispatchLoop();
  36538. /** Returns true if the stopDispatchLoop() method has been called.
  36539. */
  36540. bool hasStopMessageBeenSent() const noexcept { return quitMessagePosted; }
  36541. #if JUCE_MODAL_LOOPS_PERMITTED
  36542. /** Synchronously dispatches messages until a given time has elapsed.
  36543. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  36544. otherwise returns true.
  36545. */
  36546. bool runDispatchLoopUntil (int millisecondsToRunFor);
  36547. #endif
  36548. /** Calls a function using the message-thread.
  36549. This can be used by any thread to cause this function to be called-back
  36550. by the message thread. If it's the message-thread that's calling this method,
  36551. then the function will just be called; if another thread is calling, a message
  36552. will be posted to the queue, and this method will block until that message
  36553. is delivered, the function is called, and the result is returned.
  36554. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  36555. thread has a critical section locked, which an unrelated message callback then tries to lock
  36556. before the message thread gets round to processing this callback.
  36557. @param callback the function to call - its signature must be @code
  36558. void* myCallbackFunction (void*) @endcode
  36559. @param userData a user-defined pointer that will be passed to the function that gets called
  36560. @returns the value that the callback function returns.
  36561. @see MessageManagerLock
  36562. */
  36563. void* callFunctionOnMessageThread (MessageCallbackFunction* callback, void* userData);
  36564. /** Returns true if the caller-thread is the message thread. */
  36565. bool isThisTheMessageThread() const noexcept;
  36566. /** Called to tell the manager that the current thread is the one that's running the dispatch loop.
  36567. (Best to ignore this method unless you really know what you're doing..)
  36568. @see getCurrentMessageThread
  36569. */
  36570. void setCurrentThreadAsMessageThread();
  36571. /** Returns the ID of the current message thread, as set by setCurrentMessageThread().
  36572. (Best to ignore this method unless you really know what you're doing..)
  36573. @see setCurrentMessageThread
  36574. */
  36575. Thread::ThreadID getCurrentMessageThread() const noexcept { return messageThreadId; }
  36576. /** Returns true if the caller thread has currenltly got the message manager locked.
  36577. see the MessageManagerLock class for more info about this.
  36578. This will be true if the caller is the message thread, because that automatically
  36579. gains a lock while a message is being dispatched.
  36580. */
  36581. bool currentThreadHasLockedMessageManager() const noexcept;
  36582. /** Sends a message to all other JUCE applications that are running.
  36583. @param messageText the string that will be passed to the actionListenerCallback()
  36584. method of the broadcast listeners in the other app.
  36585. @see registerBroadcastListener, ActionListener
  36586. */
  36587. static void broadcastMessage (const String& messageText);
  36588. /** Registers a listener to get told about broadcast messages.
  36589. The actionListenerCallback() callback's string parameter
  36590. is the message passed into broadcastMessage().
  36591. @see broadcastMessage
  36592. */
  36593. void registerBroadcastListener (ActionListener* listener);
  36594. /** Deregisters a broadcast listener. */
  36595. void deregisterBroadcastListener (ActionListener* listener);
  36596. #ifndef DOXYGEN
  36597. // Internal methods - do not use!
  36598. void deliverMessage (Message*);
  36599. void deliverBroadcastMessage (const String&);
  36600. ~MessageManager() noexcept;
  36601. #endif
  36602. private:
  36603. MessageManager() noexcept;
  36604. friend class MessageListener;
  36605. friend class ChangeBroadcaster;
  36606. friend class ActionBroadcaster;
  36607. friend class CallbackMessage;
  36608. static MessageManager* instance;
  36609. SortedSet <const MessageListener*> messageListeners;
  36610. ScopedPointer <ActionBroadcaster> broadcaster;
  36611. friend class JUCEApplication;
  36612. bool quitMessagePosted, quitMessageReceived;
  36613. Thread::ThreadID messageThreadId;
  36614. friend class MessageManagerLock;
  36615. Thread::ThreadID volatile threadWithLock;
  36616. CriticalSection lockingLock;
  36617. void postMessageToQueue (Message* message);
  36618. static bool postMessageToSystemQueue (Message*);
  36619. static void* exitModalLoopCallback (void*);
  36620. static void doPlatformSpecificInitialisation();
  36621. static void doPlatformSpecificShutdown();
  36622. static bool dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  36623. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MessageManager);
  36624. };
  36625. /** Used to make sure that the calling thread has exclusive access to the message loop.
  36626. Because it's not thread-safe to call any of the Component or other UI classes
  36627. from threads other than the message thread, one of these objects can be used to
  36628. lock the message loop and allow this to be done. The message thread will be
  36629. suspended for the lifetime of the MessageManagerLock object, so create one on
  36630. the stack like this: @code
  36631. void MyThread::run()
  36632. {
  36633. someData = 1234;
  36634. const MessageManagerLock mmLock;
  36635. // the event loop will now be locked so it's safe to make a few calls..
  36636. myComponent->setBounds (newBounds);
  36637. myComponent->repaint();
  36638. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  36639. }
  36640. @endcode
  36641. Obviously be careful not to create one of these and leave it lying around, or
  36642. your app will grind to a halt!
  36643. Another caveat is that using this in conjunction with other CriticalSections
  36644. can create lots of interesting ways of producing a deadlock! In particular, if
  36645. your message thread calls stopThread() for a thread that uses these locks,
  36646. you'll get an (occasional) deadlock..
  36647. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  36648. */
  36649. class JUCE_API MessageManagerLock
  36650. {
  36651. public:
  36652. /** Tries to acquire a lock on the message manager.
  36653. The constructor attempts to gain a lock on the message loop, and the lock will be
  36654. kept for the lifetime of this object.
  36655. Optionally, you can pass a thread object here, and while waiting to obtain the lock,
  36656. this method will keep checking whether the thread has been given the
  36657. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  36658. without gaining the lock. If you pass a thread, you must check whether the lock was
  36659. successful by calling lockWasGained(). If this is false, your thread is being told to
  36660. die, so you should take evasive action.
  36661. If you pass zero for the thread object, it will wait indefinitely for the lock - be
  36662. careful when doing this, because it's very easy to deadlock if your message thread
  36663. attempts to call stopThread() on a thread just as that thread attempts to get the
  36664. message lock.
  36665. If the calling thread already has the lock, nothing will be done, so it's safe and
  36666. quick to use these locks recursively.
  36667. E.g.
  36668. @code
  36669. void run()
  36670. {
  36671. ...
  36672. while (! threadShouldExit())
  36673. {
  36674. MessageManagerLock mml (Thread::getCurrentThread());
  36675. if (! mml.lockWasGained())
  36676. return; // another thread is trying to kill us!
  36677. ..do some locked stuff here..
  36678. }
  36679. ..and now the MM is now unlocked..
  36680. }
  36681. @endcode
  36682. */
  36683. MessageManagerLock (Thread* threadToCheckForExitSignal = 0);
  36684. /** This has the same behaviour as the other constructor, but takes a ThreadPoolJob
  36685. instead of a thread.
  36686. See the MessageManagerLock (Thread*) constructor for details on how this works.
  36687. */
  36688. MessageManagerLock (ThreadPoolJob* jobToCheckForExitSignal);
  36689. /** Releases the current thread's lock on the message manager.
  36690. Make sure this object is created and deleted by the same thread,
  36691. otherwise there are no guarantees what will happen!
  36692. */
  36693. ~MessageManagerLock() noexcept;
  36694. /** Returns true if the lock was successfully acquired.
  36695. (See the constructor that takes a Thread for more info).
  36696. */
  36697. bool lockWasGained() const noexcept { return locked; }
  36698. private:
  36699. class BlockingMessage;
  36700. friend class ReferenceCountedObjectPtr<BlockingMessage>;
  36701. ReferenceCountedObjectPtr<BlockingMessage> blockingMessage;
  36702. bool locked;
  36703. void init (Thread* thread, ThreadPoolJob* job);
  36704. JUCE_DECLARE_NON_COPYABLE (MessageManagerLock);
  36705. };
  36706. #endif // __JUCE_MESSAGEMANAGER_JUCEHEADER__
  36707. /*** End of inlined file: juce_MessageManager.h ***/
  36708. #endif
  36709. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  36710. /*** Start of inlined file: juce_MultiTimer.h ***/
  36711. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  36712. #define __JUCE_MULTITIMER_JUCEHEADER__
  36713. /**
  36714. A type of timer class that can run multiple timers with different frequencies,
  36715. all of which share a single callback.
  36716. This class is very similar to the Timer class, but allows you run multiple
  36717. separate timers, where each one has a unique ID number. The methods in this
  36718. class are exactly equivalent to those in Timer, but with the addition of
  36719. this ID number.
  36720. To use it, you need to create a subclass of MultiTimer, implementing the
  36721. timerCallback() method. Then you can start timers with startTimer(), and
  36722. each time the callback is triggered, it passes in the ID of the timer that
  36723. caused it.
  36724. @see Timer
  36725. */
  36726. class JUCE_API MultiTimer
  36727. {
  36728. protected:
  36729. /** Creates a MultiTimer.
  36730. When created, no timers are running, so use startTimer() to start things off.
  36731. */
  36732. MultiTimer() noexcept;
  36733. /** Creates a copy of another timer.
  36734. Note that this timer will not contain any running timers, even if the one you're
  36735. copying from was running.
  36736. */
  36737. MultiTimer (const MultiTimer& other) noexcept;
  36738. public:
  36739. /** Destructor. */
  36740. virtual ~MultiTimer();
  36741. /** The user-defined callback routine that actually gets called by each of the
  36742. timers that are running.
  36743. It's perfectly ok to call startTimer() or stopTimer() from within this
  36744. callback to change the subsequent intervals.
  36745. */
  36746. virtual void timerCallback (int timerId) = 0;
  36747. /** Starts a timer and sets the length of interval required.
  36748. If the timer is already started, this will reset it, so the
  36749. time between calling this method and the next timer callback
  36750. will not be less than the interval length passed in.
  36751. @param timerId a unique Id number that identifies the timer to
  36752. start. This is the id that will be passed back
  36753. to the timerCallback() method when this timer is
  36754. triggered
  36755. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  36756. rounded up to 1)
  36757. */
  36758. void startTimer (int timerId, int intervalInMilliseconds) noexcept;
  36759. /** Stops a timer.
  36760. If a timer has been started with the given ID number, it will be cancelled.
  36761. No more callbacks will be made for the specified timer after this method returns.
  36762. If this is called from a different thread, any callbacks that may
  36763. be currently executing may be allowed to finish before the method
  36764. returns.
  36765. */
  36766. void stopTimer (int timerId) noexcept;
  36767. /** Checks whether a timer has been started for a specified ID.
  36768. @returns true if a timer with the given ID is running.
  36769. */
  36770. bool isTimerRunning (int timerId) const noexcept;
  36771. /** Returns the interval for a specified timer ID.
  36772. @returns the timer's interval in milliseconds if it's running, or 0 if it's no timer
  36773. is running for the ID number specified.
  36774. */
  36775. int getTimerInterval (int timerId) const noexcept;
  36776. private:
  36777. class MultiTimerCallback;
  36778. SpinLock timerListLock;
  36779. OwnedArray <MultiTimerCallback> timers;
  36780. MultiTimer& operator= (const MultiTimer&);
  36781. };
  36782. #endif // __JUCE_MULTITIMER_JUCEHEADER__
  36783. /*** End of inlined file: juce_MultiTimer.h ***/
  36784. #endif
  36785. #ifndef __JUCE_TIMER_JUCEHEADER__
  36786. #endif
  36787. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  36788. /*** Start of inlined file: juce_ArrowButton.h ***/
  36789. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  36790. #define __JUCE_ARROWBUTTON_JUCEHEADER__
  36791. /*** Start of inlined file: juce_DropShadowEffect.h ***/
  36792. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  36793. #define __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  36794. /**
  36795. An effect filter that adds a drop-shadow behind the image's content.
  36796. (This will only work on images/components that aren't opaque, of course).
  36797. When added to a component, this effect will draw a soft-edged
  36798. shadow based on what gets drawn inside it. The shadow will also
  36799. be applied to the component's children.
  36800. For speed, this doesn't use a proper gaussian blur, but cheats by
  36801. using a simple bilinear filter. If you need a really high-quality
  36802. shadow, check out ImageConvolutionKernel::createGaussianBlur()
  36803. @see Component::setComponentEffect
  36804. */
  36805. class JUCE_API DropShadowEffect : public ImageEffectFilter
  36806. {
  36807. public:
  36808. /** Creates a default drop-shadow effect.
  36809. To customise the shadow's appearance, use the setShadowProperties()
  36810. method.
  36811. */
  36812. DropShadowEffect();
  36813. /** Destructor. */
  36814. ~DropShadowEffect();
  36815. /** Sets up parameters affecting the shadow's appearance.
  36816. @param newRadius the (approximate) radius of the blur used
  36817. @param newOpacity the opacity with which the shadow is rendered
  36818. @param newShadowOffsetX allows the shadow to be shifted in relation to the
  36819. component's contents
  36820. @param newShadowOffsetY allows the shadow to be shifted in relation to the
  36821. component's contents
  36822. */
  36823. void setShadowProperties (float newRadius,
  36824. float newOpacity,
  36825. int newShadowOffsetX,
  36826. int newShadowOffsetY);
  36827. /** @internal */
  36828. void applyEffect (Image& sourceImage, Graphics& destContext, float alpha);
  36829. private:
  36830. int offsetX, offsetY;
  36831. float radius, opacity;
  36832. JUCE_LEAK_DETECTOR (DropShadowEffect);
  36833. };
  36834. #endif // __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  36835. /*** End of inlined file: juce_DropShadowEffect.h ***/
  36836. /**
  36837. A button with an arrow in it.
  36838. @see Button
  36839. */
  36840. class JUCE_API ArrowButton : public Button
  36841. {
  36842. public:
  36843. /** Creates an ArrowButton.
  36844. @param buttonName the name to give the button
  36845. @param arrowDirection the direction the arrow should point in, where 0.0 is
  36846. pointing right, 0.25 is down, 0.5 is left, 0.75 is up
  36847. @param arrowColour the colour to use for the arrow
  36848. */
  36849. ArrowButton (const String& buttonName,
  36850. float arrowDirection,
  36851. const Colour& arrowColour);
  36852. /** Destructor. */
  36853. ~ArrowButton();
  36854. protected:
  36855. /** @internal */
  36856. void paintButton (Graphics& g,
  36857. bool isMouseOverButton,
  36858. bool isButtonDown);
  36859. /** @internal */
  36860. void buttonStateChanged();
  36861. private:
  36862. Colour colour;
  36863. DropShadowEffect shadow;
  36864. Path path;
  36865. int offset;
  36866. void updateShadowAndOffset();
  36867. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ArrowButton);
  36868. };
  36869. #endif // __JUCE_ARROWBUTTON_JUCEHEADER__
  36870. /*** End of inlined file: juce_ArrowButton.h ***/
  36871. #endif
  36872. #ifndef __JUCE_BUTTON_JUCEHEADER__
  36873. #endif
  36874. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  36875. /*** Start of inlined file: juce_DrawableButton.h ***/
  36876. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  36877. #define __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  36878. /*** Start of inlined file: juce_Drawable.h ***/
  36879. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  36880. #define __JUCE_DRAWABLE_JUCEHEADER__
  36881. /*** Start of inlined file: juce_RelativeCoordinate.h ***/
  36882. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  36883. #define __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  36884. /**
  36885. Expresses a coordinate as a dynamically evaluated expression.
  36886. @see RelativePoint, RelativeRectangle
  36887. */
  36888. class JUCE_API RelativeCoordinate
  36889. {
  36890. public:
  36891. /** Creates a zero coordinate. */
  36892. RelativeCoordinate();
  36893. RelativeCoordinate (const Expression& expression);
  36894. RelativeCoordinate (const RelativeCoordinate& other);
  36895. RelativeCoordinate& operator= (const RelativeCoordinate& other);
  36896. /** Creates an absolute position from the parent origin on either the X or Y axis.
  36897. @param absoluteDistanceFromOrigin the distance from the origin
  36898. */
  36899. RelativeCoordinate (double absoluteDistanceFromOrigin);
  36900. /** Recreates a coordinate from a string description.
  36901. The string will be parsed by ExpressionParser::parse().
  36902. @param stringVersion the expression to use
  36903. @see toString
  36904. */
  36905. RelativeCoordinate (const String& stringVersion);
  36906. /** Destructor. */
  36907. ~RelativeCoordinate();
  36908. bool operator== (const RelativeCoordinate& other) const noexcept;
  36909. bool operator!= (const RelativeCoordinate& other) const noexcept;
  36910. /** Calculates the absolute position of this coordinate.
  36911. You'll need to provide a suitable Expression::Scope for looking up any coordinates that may
  36912. be needed to calculate the result.
  36913. */
  36914. double resolve (const Expression::Scope* evaluationScope) const;
  36915. /** Returns true if this coordinate uses the specified coord name at any level in its evaluation.
  36916. This will recursively check any coordinates upon which this one depends.
  36917. */
  36918. bool references (const String& coordName, const Expression::Scope* evaluationScope) const;
  36919. /** Returns true if there's a recursive loop when trying to resolve this coordinate's position. */
  36920. bool isRecursive (const Expression::Scope* evaluationScope) const;
  36921. /** Returns true if this coordinate depends on any other coordinates for its position. */
  36922. bool isDynamic() const;
  36923. /** Changes the value of this coord to make it resolve to the specified position.
  36924. Calling this will leave the anchor points unchanged, but will set this coordinate's absolute
  36925. or relative position to whatever value is necessary to make its resultant position
  36926. match the position that is provided.
  36927. */
  36928. void moveToAbsolute (double absoluteTargetPosition, const Expression::Scope* evaluationScope);
  36929. /** Returns the expression that defines this coordinate. */
  36930. const Expression& getExpression() const { return term; }
  36931. /** Returns a string which represents this coordinate.
  36932. For details of the string syntax, see the constructor notes.
  36933. */
  36934. String toString() const;
  36935. /** A set of static strings that are commonly used by the RelativeCoordinate class.
  36936. As well as avoiding using string literals in your code, using these preset values
  36937. has the advantage that all instances of the same string will share the same, reference-counted
  36938. String object, so if you have thousands of points which all refer to the same
  36939. anchor points, this can save a significant amount of memory allocation.
  36940. */
  36941. struct Strings
  36942. {
  36943. static const String parent; /**< "parent" */
  36944. static const String left; /**< "left" */
  36945. static const String right; /**< "right" */
  36946. static const String top; /**< "top" */
  36947. static const String bottom; /**< "bottom" */
  36948. static const String x; /**< "x" */
  36949. static const String y; /**< "y" */
  36950. static const String width; /**< "width" */
  36951. static const String height; /**< "height" */
  36952. };
  36953. struct StandardStrings
  36954. {
  36955. enum Type
  36956. {
  36957. left, right, top, bottom,
  36958. x, y, width, height,
  36959. parent,
  36960. unknown
  36961. };
  36962. static Type getTypeOf (const String& s) noexcept;
  36963. };
  36964. private:
  36965. Expression term;
  36966. };
  36967. #endif // __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  36968. /*** End of inlined file: juce_RelativeCoordinate.h ***/
  36969. /*** Start of inlined file: juce_RelativeCoordinatePositioner.h ***/
  36970. #ifndef __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  36971. #define __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  36972. /*** Start of inlined file: juce_RelativePoint.h ***/
  36973. #ifndef __JUCE_RELATIVEPOINT_JUCEHEADER__
  36974. #define __JUCE_RELATIVEPOINT_JUCEHEADER__
  36975. /**
  36976. An X-Y position stored as a pair of RelativeCoordinate values.
  36977. @see RelativeCoordinate, RelativeRectangle
  36978. */
  36979. class JUCE_API RelativePoint
  36980. {
  36981. public:
  36982. /** Creates a point at the origin. */
  36983. RelativePoint();
  36984. /** Creates an absolute point, relative to the origin. */
  36985. RelativePoint (const Point<float>& absolutePoint);
  36986. /** Creates an absolute point, relative to the origin. */
  36987. RelativePoint (float absoluteX, float absoluteY);
  36988. /** Creates an absolute point from two coordinates. */
  36989. RelativePoint (const RelativeCoordinate& x, const RelativeCoordinate& y);
  36990. /** Creates a point from a stringified representation.
  36991. The string must contain a pair of coordinates, separated by space or a comma. The syntax for the coordinate
  36992. strings is explained in the RelativeCoordinate class.
  36993. @see toString
  36994. */
  36995. RelativePoint (const String& stringVersion);
  36996. bool operator== (const RelativePoint& other) const noexcept;
  36997. bool operator!= (const RelativePoint& other) const noexcept;
  36998. /** Calculates the absolute position of this point.
  36999. You'll need to provide a suitable Expression::Scope for looking up any coordinates that may
  37000. be needed to calculate the result.
  37001. */
  37002. const Point<float> resolve (const Expression::Scope* evaluationContext) const;
  37003. /** Changes the values of this point's coordinates to make it resolve to the specified position.
  37004. Calling this will leave any anchor points unchanged, but will set any absolute
  37005. or relative positions to whatever values are necessary to make the resultant position
  37006. match the position that is provided.
  37007. */
  37008. void moveToAbsolute (const Point<float>& newPos, const Expression::Scope* evaluationContext);
  37009. /** Returns a string which represents this point.
  37010. This returns a comma-separated pair of coordinates. For details of the string syntax used by the
  37011. coordinates, see the RelativeCoordinate constructor notes.
  37012. The string that is returned can be passed to the RelativePoint constructor to recreate the point.
  37013. */
  37014. String toString() const;
  37015. /** Returns true if this point depends on any other coordinates for its position. */
  37016. bool isDynamic() const;
  37017. // The actual X and Y coords...
  37018. RelativeCoordinate x, y;
  37019. };
  37020. #endif // __JUCE_RELATIVEPOINT_JUCEHEADER__
  37021. /*** End of inlined file: juce_RelativePoint.h ***/
  37022. /*** Start of inlined file: juce_MarkerList.h ***/
  37023. #ifndef __JUCE_MARKERLIST_JUCEHEADER__
  37024. #define __JUCE_MARKERLIST_JUCEHEADER__
  37025. class Component;
  37026. /**
  37027. Holds a set of named marker points along a one-dimensional axis.
  37028. This class is used to store sets of X and Y marker points in components.
  37029. @see Component::getMarkers().
  37030. */
  37031. class JUCE_API MarkerList
  37032. {
  37033. public:
  37034. /** Creates an empty marker list. */
  37035. MarkerList();
  37036. /** Creates a copy of another marker list. */
  37037. MarkerList (const MarkerList& other);
  37038. /** Copies another marker list to this one. */
  37039. MarkerList& operator= (const MarkerList& other);
  37040. /** Destructor. */
  37041. ~MarkerList();
  37042. /** Represents a marker in a MarkerList. */
  37043. class JUCE_API Marker
  37044. {
  37045. public:
  37046. /** Creates a copy of another Marker. */
  37047. Marker (const Marker& other);
  37048. /** Creates a Marker with a given name and position. */
  37049. Marker (const String& name, const RelativeCoordinate& position);
  37050. /** The marker's name. */
  37051. String name;
  37052. /** The marker's position.
  37053. The expression used to define the coordinate may use the names of other
  37054. markers, so that markers can be linked in arbitrary ways, but be careful
  37055. not to create recursive loops of markers whose positions are based on each
  37056. other! It can also refer to "parent.right" and "parent.bottom" so that you
  37057. can set markers which are relative to the size of the component that contains
  37058. them.
  37059. To resolve the coordinate, you can use the MarkerList::getMarkerPosition() method.
  37060. */
  37061. RelativeCoordinate position;
  37062. /** Returns true if both the names and positions of these two markers match. */
  37063. bool operator== (const Marker&) const noexcept;
  37064. /** Returns true if either the name or position of these two markers differ. */
  37065. bool operator!= (const Marker&) const noexcept;
  37066. };
  37067. /** Returns the number of markers in the list. */
  37068. int getNumMarkers() const noexcept;
  37069. /** Returns one of the markers in the list, by its index. */
  37070. const Marker* getMarker (int index) const noexcept;
  37071. /** Returns a named marker, or 0 if no such name is found.
  37072. Note that name comparisons are case-sensitive.
  37073. */
  37074. const Marker* getMarker (const String& name) const noexcept;
  37075. /** Evaluates the given marker and returns its absolute position.
  37076. The parent component must be supplied in case the marker's expression refers to
  37077. the size of its parent component.
  37078. */
  37079. double getMarkerPosition (const Marker& marker, Component* parentComponent) const;
  37080. /** Sets the position of a marker.
  37081. If the name already exists, then the existing marker is moved; if it doesn't exist, then a
  37082. new marker is added.
  37083. */
  37084. void setMarker (const String& name, const RelativeCoordinate& position);
  37085. /** Deletes the marker at the given list index. */
  37086. void removeMarker (int index);
  37087. /** Deletes the marker with the given name. */
  37088. void removeMarker (const String& name);
  37089. /** Returns true if all the markers in these two lists match exactly. */
  37090. bool operator== (const MarkerList& other) const noexcept;
  37091. /** Returns true if not all the markers in these two lists match exactly. */
  37092. bool operator!= (const MarkerList& other) const noexcept;
  37093. /**
  37094. A class for receiving events when changes are made to a MarkerList.
  37095. You can register a MarkerList::Listener with a MarkerList using the MarkerList::addListener()
  37096. method, and it will be called when markers are moved, added, or deleted.
  37097. @see MarkerList::addListener, MarkerList::removeListener
  37098. */
  37099. class JUCE_API Listener
  37100. {
  37101. public:
  37102. /** Destructor. */
  37103. virtual ~Listener() {}
  37104. /** Called when something in the given marker list changes. */
  37105. virtual void markersChanged (MarkerList* markerList) = 0;
  37106. /** Called when the given marker list is being deleted. */
  37107. virtual void markerListBeingDeleted (MarkerList* markerList);
  37108. };
  37109. /** Registers a listener that will be called when the markers are changed. */
  37110. void addListener (Listener* listener);
  37111. /** Deregisters a previously-registered listener. */
  37112. void removeListener (Listener* listener);
  37113. /** Synchronously calls markersChanged() on all the registered listeners. */
  37114. void markersHaveChanged();
  37115. /** Forms a wrapper around a ValueTree that can be used for storing a MarkerList. */
  37116. class ValueTreeWrapper
  37117. {
  37118. public:
  37119. ValueTreeWrapper (const ValueTree& state);
  37120. ValueTree& getState() noexcept { return state; }
  37121. int getNumMarkers() const;
  37122. ValueTree getMarkerState (int index) const;
  37123. ValueTree getMarkerState (const String& name) const;
  37124. bool containsMarker (const ValueTree& state) const;
  37125. MarkerList::Marker getMarker (const ValueTree& state) const;
  37126. void setMarker (const MarkerList::Marker& marker, UndoManager* undoManager);
  37127. void removeMarker (const ValueTree& state, UndoManager* undoManager);
  37128. void applyTo (MarkerList& markerList);
  37129. void readFrom (const MarkerList& markerList, UndoManager* undoManager);
  37130. static const Identifier markerTag, nameProperty, posProperty;
  37131. private:
  37132. ValueTree state;
  37133. };
  37134. private:
  37135. OwnedArray<Marker> markers;
  37136. ListenerList<Listener> listeners;
  37137. JUCE_LEAK_DETECTOR (MarkerList);
  37138. };
  37139. #endif // __JUCE_MARKERLIST_JUCEHEADER__
  37140. /*** End of inlined file: juce_MarkerList.h ***/
  37141. /**
  37142. Base class for Component::Positioners that are based upon relative coordinates.
  37143. */
  37144. class JUCE_API RelativeCoordinatePositionerBase : public Component::Positioner,
  37145. public ComponentListener,
  37146. public MarkerList::Listener
  37147. {
  37148. public:
  37149. RelativeCoordinatePositionerBase (Component& component_);
  37150. ~RelativeCoordinatePositionerBase();
  37151. void componentMovedOrResized (Component&, bool, bool);
  37152. void componentParentHierarchyChanged (Component&);
  37153. void componentChildrenChanged (Component& component);
  37154. void componentBeingDeleted (Component& component);
  37155. void markersChanged (MarkerList*);
  37156. void markerListBeingDeleted (MarkerList* markerList);
  37157. void apply();
  37158. bool addCoordinate (const RelativeCoordinate& coord);
  37159. bool addPoint (const RelativePoint& point);
  37160. /** Used for resolving a RelativeCoordinate expression in the context of a component. */
  37161. class ComponentScope : public Expression::Scope
  37162. {
  37163. public:
  37164. ComponentScope (Component& component_);
  37165. Expression getSymbolValue (const String& symbol) const;
  37166. void visitRelativeScope (const String& scopeName, Visitor& visitor) const;
  37167. String getScopeUID() const;
  37168. protected:
  37169. Component& component;
  37170. Component* findSiblingComponent (const String& componentID) const;
  37171. const MarkerList::Marker* findMarker (const String& name, MarkerList*& list) const;
  37172. private:
  37173. JUCE_DECLARE_NON_COPYABLE (ComponentScope);
  37174. };
  37175. protected:
  37176. virtual bool registerCoordinates() = 0;
  37177. virtual void applyToComponentBounds() = 0;
  37178. private:
  37179. class DependencyFinderScope;
  37180. friend class DependencyFinderScope;
  37181. Array <Component*> sourceComponents;
  37182. Array <MarkerList*> sourceMarkerLists;
  37183. bool registeredOk;
  37184. void registerComponentListener (Component& comp);
  37185. void registerMarkerListListener (MarkerList* const list);
  37186. void unregisterListeners();
  37187. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativeCoordinatePositionerBase);
  37188. };
  37189. #endif // __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  37190. /*** End of inlined file: juce_RelativeCoordinatePositioner.h ***/
  37191. /*** Start of inlined file: juce_ComponentBuilder.h ***/
  37192. #ifndef __JUCE_COMPONENTBUILDER_JUCEHEADER__
  37193. #define __JUCE_COMPONENTBUILDER_JUCEHEADER__
  37194. /**
  37195. Loads and maintains a tree of Components from a ValueTree that represents them.
  37196. To allow the state of a tree of components to be saved as a ValueTree and re-loaded,
  37197. this class lets you register a set of type-handlers for the different components that
  37198. are involved, and then uses these types to re-create a set of components from its
  37199. stored state.
  37200. Essentially, to use this, you need to create a ComponentBuilder with your ValueTree,
  37201. then use registerTypeHandler() to give it a set of type handlers that can cope with
  37202. all the items in your tree. Then you can call getComponent() to build the component.
  37203. Once you've got the component you can either take it and delete the ComponentBuilder
  37204. object, or if you keep the ComponentBuilder around, it'll monitor any changes in the
  37205. ValueTree and automatically update the component to reflect these changes.
  37206. */
  37207. class JUCE_API ComponentBuilder : public ValueTree::Listener
  37208. {
  37209. public:
  37210. /** Creates a ComponentBuilder that will use the given state.
  37211. Once you've created your builder, you should use registerTypeHandler() to register some
  37212. type handlers for it, and then you can call createComponent() or getManagedComponent()
  37213. to get the actual component.
  37214. */
  37215. explicit ComponentBuilder (const ValueTree& state);
  37216. /** Destructor. */
  37217. ~ComponentBuilder();
  37218. /** Returns the ValueTree that this builder is working with. */
  37219. ValueTree& getState() noexcept { return state; }
  37220. /** Returns the ValueTree that this builder is working with. */
  37221. const ValueTree& getState() const noexcept { return state; }
  37222. /** Returns the builder's component (creating it if necessary).
  37223. The first time that this method is called, the builder will attempt to create a component
  37224. from the ValueTree, so you must have registered some suitable type handlers before calling
  37225. this. If there's a problem and the component can't be created, this method returns 0.
  37226. The component that is returned is owned by this ComponentBuilder, so you can put it inside
  37227. your own parent components, but don't delete it! The ComponentBuilder will delete it automatically
  37228. when the builder is destroyed. If you want to get a component that you can delete yourself,
  37229. call createComponent() instead.
  37230. The ComponentBuilder will update this component if any changes are made to the ValueTree, so if
  37231. there's a chance that the tree might change, be careful not to keep any pointers to sub-components,
  37232. as they may be changed or removed.
  37233. */
  37234. Component* getManagedComponent();
  37235. /** Creates and returns a new instance of the component that the ValueTree represents.
  37236. The caller is responsible for using and deleting the object that is returned. Unlike
  37237. getManagedComponent(), the component that is returned will not be updated by the builder.
  37238. */
  37239. Component* createComponent();
  37240. /**
  37241. The class is a base class for objects that manage the loading of a type of component
  37242. from a ValueTree.
  37243. To store and re-load a tree of components as a ValueTree, each component type must have
  37244. a TypeHandler to represent it.
  37245. @see ComponentBuilder::registerTypeHandler(), Drawable::registerDrawableTypeHandlers()
  37246. */
  37247. class JUCE_API TypeHandler
  37248. {
  37249. public:
  37250. /** Creates a TypeHandler.
  37251. The valueTreeType must be the type name of the ValueTrees that this handler can parse.
  37252. */
  37253. explicit TypeHandler (const Identifier& valueTreeType);
  37254. /** Destructor. */
  37255. virtual ~TypeHandler();
  37256. /** Returns the type of the ValueTrees that this handler can parse. */
  37257. const Identifier& getType() const noexcept { return valueTreeType; }
  37258. /** Returns the builder that this type is registered with. */
  37259. ComponentBuilder* getBuilder() const noexcept;
  37260. /** This method must create a new component from the given state, add it to the specified
  37261. parent component (which may be null), and return it.
  37262. The ValueTree will have been pre-checked to make sure that its type matches the type
  37263. that this handler supports.
  37264. There's no need to set the new Component's ID to match that of the state - the builder
  37265. will take care of that itself.
  37266. */
  37267. virtual Component* addNewComponentFromState (const ValueTree& state, Component* parent) = 0;
  37268. /** This method must update an existing component from a new ValueTree state.
  37269. A component that has been created with addNewComponentFromState() may need to be updated
  37270. if the ValueTree changes, so this method is used to do that. Your implementation must do
  37271. whatever's necessary to update the component from the new state provided.
  37272. The ValueTree will have been pre-checked to make sure that its type matches the type
  37273. that this handler supports, and the component will have been created by this type's
  37274. addNewComponentFromState() method.
  37275. */
  37276. virtual void updateComponentFromState (Component* component, const ValueTree& state) = 0;
  37277. private:
  37278. friend class ComponentBuilder;
  37279. ComponentBuilder* builder;
  37280. const Identifier valueTreeType;
  37281. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TypeHandler);
  37282. };
  37283. /** Adds a type handler that the builder can use when trying to load components.
  37284. @see Drawable::registerDrawableTypeHandlers()
  37285. */
  37286. void registerTypeHandler (TypeHandler* type);
  37287. /** Tries to find a registered type handler that can load a component from the given ValueTree. */
  37288. TypeHandler* getHandlerForState (const ValueTree& state) const;
  37289. /** Returns the number of registered type handlers.
  37290. @see getHandler, registerTypeHandler
  37291. */
  37292. int getNumHandlers() const noexcept;
  37293. /** Returns one of the registered type handlers.
  37294. @see getNumHandlers, registerTypeHandler
  37295. */
  37296. TypeHandler* getHandler (int index) const noexcept;
  37297. /** This class is used when references to images need to be stored in ValueTrees.
  37298. An instance of an ImageProvider provides a mechanism for converting an Image to/from
  37299. a reference, which may be a file, URL, ID string, or whatever system is appropriate in
  37300. your app.
  37301. When you're loading components from a ValueTree that may need a way of loading images, you
  37302. should call ComponentBuilder::setImageProvider() to supply a suitable provider before
  37303. trying to load the component.
  37304. @see ComponentBuilder::setImageProvider()
  37305. */
  37306. class JUCE_API ImageProvider
  37307. {
  37308. public:
  37309. ImageProvider() {}
  37310. virtual ~ImageProvider() {}
  37311. /** Retrieves the image associated with this identifier, which could be any
  37312. kind of string, number, filename, etc.
  37313. The image that is returned will be owned by the caller, but it may come
  37314. from the ImageCache.
  37315. */
  37316. virtual Image getImageForIdentifier (const var& imageIdentifier) = 0;
  37317. /** Returns an identifier to be used to refer to a given image.
  37318. This is used when a reference to an image is stored in a ValueTree.
  37319. */
  37320. virtual var getIdentifierForImage (const Image& image) = 0;
  37321. };
  37322. /** Gives the builder an ImageProvider object that the type handlers can use when
  37323. loading images from stored references.
  37324. The object that is passed in is not owned by the builder, so the caller must delete
  37325. it when it is no longer needed, but not while the builder may still be using it. To
  37326. clear the image provider, just call setImageProvider (nullptr).
  37327. */
  37328. void setImageProvider (ImageProvider* newImageProvider) noexcept;
  37329. /** Returns the current image provider that this builder is using, or 0 if none has been set. */
  37330. ImageProvider* getImageProvider() const noexcept;
  37331. /** Updates the children of a parent component by updating them from the children of
  37332. a given ValueTree.
  37333. */
  37334. void updateChildComponents (Component& parent, const ValueTree& children);
  37335. /** An identifier for the property of the ValueTrees that is used to store a unique ID
  37336. for that component.
  37337. */
  37338. static const Identifier idProperty;
  37339. /** @internal */
  37340. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& property);
  37341. /** @internal */
  37342. void valueTreeChildAdded (ValueTree& parentTree, ValueTree& childWhichHasBeenAdded);
  37343. /** @internal */
  37344. void valueTreeChildRemoved (ValueTree& parentTree, ValueTree& childWhichHasBeenRemoved);
  37345. /** @internal */
  37346. void valueTreeChildOrderChanged (ValueTree& parentTree);
  37347. /** @internal */
  37348. void valueTreeParentChanged (ValueTree& treeWhoseParentHasChanged);
  37349. private:
  37350. ValueTree state;
  37351. OwnedArray <TypeHandler> types;
  37352. ScopedPointer<Component> component;
  37353. ImageProvider* imageProvider;
  37354. #if JUCE_DEBUG
  37355. WeakReference<Component> componentRef;
  37356. #endif
  37357. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentBuilder);
  37358. };
  37359. #endif // __JUCE_COMPONENTBUILDER_JUCEHEADER__
  37360. /*** End of inlined file: juce_ComponentBuilder.h ***/
  37361. class DrawableComposite;
  37362. /**
  37363. The base class for objects which can draw themselves, e.g. polygons, images, etc.
  37364. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  37365. */
  37366. class JUCE_API Drawable : public Component
  37367. {
  37368. protected:
  37369. /** The base class can't be instantiated directly.
  37370. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  37371. */
  37372. Drawable();
  37373. public:
  37374. /** Destructor. */
  37375. virtual ~Drawable();
  37376. /** Creates a deep copy of this Drawable object.
  37377. Use this to create a new copy of this and any sub-objects in the tree.
  37378. */
  37379. virtual Drawable* createCopy() const = 0;
  37380. /** Renders this Drawable object.
  37381. Note that the preferred way to render a drawable in future is by using it
  37382. as a component and adding it to a parent, so you might want to consider that
  37383. before using this method.
  37384. @see drawWithin
  37385. */
  37386. void draw (Graphics& g, float opacity,
  37387. const AffineTransform& transform = AffineTransform::identity) const;
  37388. /** Renders the Drawable at a given offset within the Graphics context.
  37389. The co-ordinates passed-in are used to translate the object relative to its own
  37390. origin before drawing it - this is basically a quick way of saying:
  37391. @code
  37392. draw (g, AffineTransform::translation (x, y)).
  37393. @endcode
  37394. Note that the preferred way to render a drawable in future is by using it
  37395. as a component and adding it to a parent, so you might want to consider that
  37396. before using this method.
  37397. */
  37398. void drawAt (Graphics& g, float x, float y, float opacity) const;
  37399. /** Renders the Drawable within a rectangle, scaling it to fit neatly inside without
  37400. changing its aspect-ratio.
  37401. The object can placed arbitrarily within the rectangle based on a Justification type,
  37402. and can either be made as big as possible, or just reduced to fit.
  37403. Note that the preferred way to render a drawable in future is by using it
  37404. as a component and adding it to a parent, so you might want to consider that
  37405. before using this method.
  37406. @param g the graphics context to render onto
  37407. @param destArea the target rectangle to fit the drawable into
  37408. @param placement defines the alignment and rescaling to use to fit
  37409. this object within the target rectangle.
  37410. @param opacity the opacity to use, in the range 0 to 1.0
  37411. */
  37412. void drawWithin (Graphics& g,
  37413. const Rectangle<float>& destArea,
  37414. const RectanglePlacement& placement,
  37415. float opacity) const;
  37416. /** Resets any transformations on this drawable, and positions its origin within
  37417. its parent component.
  37418. */
  37419. void setOriginWithOriginalSize (const Point<float>& originWithinParent);
  37420. /** Sets a transform for this drawable that will position it within the specified
  37421. area of its parent component.
  37422. */
  37423. void setTransformToFit (const Rectangle<float>& areaInParent, const RectanglePlacement& placement);
  37424. /** Returns the DrawableComposite that contains this object, if there is one. */
  37425. DrawableComposite* getParent() const;
  37426. /** Tries to turn some kind of image file into a drawable.
  37427. The data could be an image that the ImageFileFormat class understands, or it
  37428. could be SVG.
  37429. */
  37430. static Drawable* createFromImageData (const void* data, size_t numBytes);
  37431. /** Tries to turn a stream containing some kind of image data into a drawable.
  37432. The data could be an image that the ImageFileFormat class understands, or it
  37433. could be SVG.
  37434. */
  37435. static Drawable* createFromImageDataStream (InputStream& dataSource);
  37436. /** Tries to turn a file containing some kind of image data into a drawable.
  37437. The data could be an image that the ImageFileFormat class understands, or it
  37438. could be SVG.
  37439. */
  37440. static Drawable* createFromImageFile (const File& file);
  37441. /** Attempts to parse an SVG (Scalable Vector Graphics) document, and to turn this
  37442. into a Drawable tree.
  37443. The object returned must be deleted by the caller. If something goes wrong
  37444. while parsing, it may return 0.
  37445. SVG is a pretty large and complex spec, and this doesn't aim to be a full
  37446. implementation, but it can return the basic vector objects.
  37447. */
  37448. static Drawable* createFromSVG (const XmlElement& svgDocument);
  37449. /** Tries to create a Drawable from a previously-saved ValueTree.
  37450. The ValueTree must have been created by the createValueTree() method.
  37451. If there are any images used within the drawable, you'll need to provide a valid
  37452. ImageProvider object that can be used to retrieve these images from whatever type
  37453. of identifier is used to represent them.
  37454. Internally, this uses a ComponentBuilder, and registerDrawableTypeHandlers().
  37455. */
  37456. static Drawable* createFromValueTree (const ValueTree& tree, ComponentBuilder::ImageProvider* imageProvider);
  37457. /** Creates a ValueTree to represent this Drawable.
  37458. The ValueTree that is returned can be turned back into a Drawable with createFromValueTree().
  37459. If there are any images used in this drawable, you'll need to provide a valid ImageProvider
  37460. object that can be used to create storable representations of them.
  37461. */
  37462. virtual ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const = 0;
  37463. /** Returns the area that this drawble covers.
  37464. The result is expressed in this drawable's own coordinate space, and does not take
  37465. into account any transforms that may be applied to the component.
  37466. */
  37467. virtual Rectangle<float> getDrawableBounds() const = 0;
  37468. /** Internal class used to manage ValueTrees that represent Drawables. */
  37469. class ValueTreeWrapperBase
  37470. {
  37471. public:
  37472. ValueTreeWrapperBase (const ValueTree& state);
  37473. ValueTree& getState() noexcept { return state; }
  37474. String getID() const;
  37475. void setID (const String& newID);
  37476. ValueTree state;
  37477. };
  37478. /** Registers a set of ComponentBuilder::TypeHandler objects that can be used to
  37479. load all the different Drawable types from a saved state.
  37480. @see ComponentBuilder::registerTypeHandler()
  37481. */
  37482. static void registerDrawableTypeHandlers (ComponentBuilder& componentBuilder);
  37483. protected:
  37484. friend class DrawableComposite;
  37485. friend class DrawableShape;
  37486. /** @internal */
  37487. void transformContextToCorrectOrigin (Graphics& g);
  37488. /** @internal */
  37489. void parentHierarchyChanged();
  37490. /** @internal */
  37491. void setBoundsToEnclose (const Rectangle<float>& area);
  37492. Point<int> originRelativeToComponent;
  37493. #ifndef DOXYGEN
  37494. /** Internal utility class used by Drawables. */
  37495. template <class DrawableType>
  37496. class Positioner : public RelativeCoordinatePositionerBase
  37497. {
  37498. public:
  37499. Positioner (DrawableType& component_)
  37500. : RelativeCoordinatePositionerBase (component_),
  37501. owner (component_)
  37502. {}
  37503. bool registerCoordinates() { return owner.registerCoordinates (*this); }
  37504. void applyToComponentBounds()
  37505. {
  37506. ComponentScope scope (getComponent());
  37507. owner.recalculateCoordinates (&scope);
  37508. }
  37509. void applyNewBounds (const Rectangle<int>&)
  37510. {
  37511. jassertfalse; // drawables can't be resized directly!
  37512. }
  37513. private:
  37514. DrawableType& owner;
  37515. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Positioner);
  37516. };
  37517. #endif
  37518. private:
  37519. void nonConstDraw (Graphics& g, float opacity, const AffineTransform& transform);
  37520. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Drawable);
  37521. };
  37522. #endif // __JUCE_DRAWABLE_JUCEHEADER__
  37523. /*** End of inlined file: juce_Drawable.h ***/
  37524. /**
  37525. A button that displays a Drawable.
  37526. Up to three Drawable objects can be given to this button, to represent the
  37527. 'normal', 'over' and 'down' states.
  37528. @see Button
  37529. */
  37530. class JUCE_API DrawableButton : public Button
  37531. {
  37532. public:
  37533. enum ButtonStyle
  37534. {
  37535. ImageFitted, /**< The button will just display the images, but will resize and centre them to fit inside it. */
  37536. ImageRaw, /**< The button will just display the images in their normal size and position.
  37537. This leaves it up to the caller to make sure the images are the correct size and position for the button. */
  37538. ImageAboveTextLabel, /**< Draws the button as a text label across the bottom with the image resized and scaled to fit above it. */
  37539. ImageOnButtonBackground /**< Draws the button as a standard rounded-rectangle button with the image on top. */
  37540. };
  37541. /** Creates a DrawableButton.
  37542. After creating one of these, use setImages() to specify the drawables to use.
  37543. @param buttonName the name to give the component
  37544. @param buttonStyle the layout to use
  37545. @see ButtonStyle, setButtonStyle, setImages
  37546. */
  37547. DrawableButton (const String& buttonName,
  37548. ButtonStyle buttonStyle);
  37549. /** Destructor. */
  37550. ~DrawableButton();
  37551. /** Sets up the images to draw for the various button states.
  37552. The button will keep its own internal copies of these drawables.
  37553. @param normalImage the thing to draw for the button's 'normal' state. An internal copy
  37554. will be made of the object passed-in if it is non-zero.
  37555. @param overImage the thing to draw for the button's 'over' state - if this is
  37556. zero, the button's normal image will be used when the mouse is
  37557. over it. An internal copy will be made of the object passed-in
  37558. if it is non-zero.
  37559. @param downImage the thing to draw for the button's 'down' state - if this is
  37560. zero, the 'over' image will be used instead (or the normal image
  37561. as a last resort). An internal copy will be made of the object
  37562. passed-in if it is non-zero.
  37563. @param disabledImage an image to draw when the button is disabled. If this is zero,
  37564. the normal image will be drawn with a reduced opacity instead.
  37565. An internal copy will be made of the object passed-in if it is
  37566. non-zero.
  37567. @param normalImageOn same as the normalImage, but this is used when the button's toggle
  37568. state is 'on'. If this is 0, the normal image is used instead
  37569. @param overImageOn same as the overImage, but this is used when the button's toggle
  37570. state is 'on'. If this is 0, the normalImageOn is drawn instead
  37571. @param downImageOn same as the downImage, but this is used when the button's toggle
  37572. state is 'on'. If this is 0, the overImageOn is drawn instead
  37573. @param disabledImageOn same as the disabledImage, but this is used when the button's toggle
  37574. state is 'on'. If this is 0, the normal image will be drawn instead
  37575. with a reduced opacity
  37576. */
  37577. void setImages (const Drawable* normalImage,
  37578. const Drawable* overImage = nullptr,
  37579. const Drawable* downImage = nullptr,
  37580. const Drawable* disabledImage = nullptr,
  37581. const Drawable* normalImageOn = nullptr,
  37582. const Drawable* overImageOn = nullptr,
  37583. const Drawable* downImageOn = nullptr,
  37584. const Drawable* disabledImageOn = nullptr);
  37585. /** Changes the button's style.
  37586. @see ButtonStyle
  37587. */
  37588. void setButtonStyle (ButtonStyle newStyle);
  37589. /** Changes the button's background colours.
  37590. The toggledOffColour is the colour to use when the button's toggle state
  37591. is off, and toggledOnColour when it's on.
  37592. For an ImageOnly or ImageAboveTextLabel style, the background colour is
  37593. used to fill the background of the component.
  37594. For an ImageOnButtonBackground style, the colour is used to draw the
  37595. button's lozenge shape and exactly how the colour's used will depend
  37596. on the LookAndFeel.
  37597. */
  37598. void setBackgroundColours (const Colour& toggledOffColour,
  37599. const Colour& toggledOnColour);
  37600. /** Returns the current background colour being used.
  37601. @see setBackgroundColour
  37602. */
  37603. const Colour& getBackgroundColour() const noexcept;
  37604. /** Gives the button an optional amount of space around the edge of the drawable.
  37605. This will only apply to ImageFitted or ImageRaw styles, it won't affect the
  37606. ones on a button background. If the button is too small for the given gap, a
  37607. smaller gap will be used.
  37608. By default there's a gap of about 3 pixels.
  37609. */
  37610. void setEdgeIndent (int numPixelsIndent);
  37611. /** Returns the image that the button is currently displaying. */
  37612. Drawable* getCurrentImage() const noexcept;
  37613. Drawable* getNormalImage() const noexcept;
  37614. Drawable* getOverImage() const noexcept;
  37615. Drawable* getDownImage() const noexcept;
  37616. /** A set of colour IDs to use to change the colour of various aspects of the link.
  37617. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37618. methods.
  37619. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37620. */
  37621. enum ColourIds
  37622. {
  37623. textColourId = 0x1004010, /**< The colour to use for the URL text. */
  37624. };
  37625. protected:
  37626. /** @internal */
  37627. void paintButton (Graphics& g,
  37628. bool isMouseOverButton,
  37629. bool isButtonDown);
  37630. /** @internal */
  37631. void buttonStateChanged();
  37632. /** @internal */
  37633. void resized();
  37634. private:
  37635. ButtonStyle style;
  37636. ScopedPointer <Drawable> normalImage, overImage, downImage, disabledImage;
  37637. ScopedPointer <Drawable> normalImageOn, overImageOn, downImageOn, disabledImageOn;
  37638. Drawable* currentImage;
  37639. Colour backgroundOff, backgroundOn;
  37640. int edgeIndent;
  37641. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DrawableButton);
  37642. };
  37643. #endif // __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  37644. /*** End of inlined file: juce_DrawableButton.h ***/
  37645. #endif
  37646. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  37647. /*** Start of inlined file: juce_HyperlinkButton.h ***/
  37648. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  37649. #define __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  37650. /**
  37651. A button showing an underlined weblink, that will launch the link
  37652. when it's clicked.
  37653. @see Button
  37654. */
  37655. class JUCE_API HyperlinkButton : public Button
  37656. {
  37657. public:
  37658. /** Creates a HyperlinkButton.
  37659. @param linkText the text that will be displayed in the button - this is
  37660. also set as the Component's name, but the text can be
  37661. changed later with the Button::getButtonText() method
  37662. @param linkURL the URL to launch when the user clicks the button
  37663. */
  37664. HyperlinkButton (const String& linkText,
  37665. const URL& linkURL);
  37666. /** Destructor. */
  37667. ~HyperlinkButton();
  37668. /** Changes the font to use for the text.
  37669. If resizeToMatchComponentHeight is true, the font's height will be adjusted
  37670. to match the size of the component.
  37671. */
  37672. void setFont (const Font& newFont,
  37673. bool resizeToMatchComponentHeight,
  37674. const Justification& justificationType = Justification::horizontallyCentred);
  37675. /** A set of colour IDs to use to change the colour of various aspects of the link.
  37676. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37677. methods.
  37678. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37679. */
  37680. enum ColourIds
  37681. {
  37682. textColourId = 0x1001f00, /**< The colour to use for the URL text. */
  37683. };
  37684. /** Changes the URL that the button will trigger. */
  37685. void setURL (const URL& newURL) noexcept;
  37686. /** Returns the URL that the button will trigger. */
  37687. const URL& getURL() const noexcept { return url; }
  37688. /** Resizes the button horizontally to fit snugly around the text.
  37689. This won't affect the button's height.
  37690. */
  37691. void changeWidthToFitText();
  37692. protected:
  37693. /** @internal */
  37694. void clicked();
  37695. /** @internal */
  37696. void colourChanged();
  37697. /** @internal */
  37698. void paintButton (Graphics& g,
  37699. bool isMouseOverButton,
  37700. bool isButtonDown);
  37701. private:
  37702. URL url;
  37703. Font font;
  37704. bool resizeFont;
  37705. Justification justification;
  37706. Font getFontToUse() const;
  37707. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HyperlinkButton);
  37708. };
  37709. #endif // __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  37710. /*** End of inlined file: juce_HyperlinkButton.h ***/
  37711. #endif
  37712. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  37713. /*** Start of inlined file: juce_ImageButton.h ***/
  37714. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  37715. #define __JUCE_IMAGEBUTTON_JUCEHEADER__
  37716. /**
  37717. As the title suggests, this is a button containing an image.
  37718. The colour and transparency of the image can be set to vary when the
  37719. button state changes.
  37720. @see Button, ShapeButton, TextButton
  37721. */
  37722. class JUCE_API ImageButton : public Button
  37723. {
  37724. public:
  37725. /** Creates an ImageButton.
  37726. Use setImage() to specify the image to use. The colours and opacities that
  37727. are specified here can be changed later using setDrawingOptions().
  37728. @param name the name to give the component
  37729. */
  37730. explicit ImageButton (const String& name);
  37731. /** Destructor. */
  37732. ~ImageButton();
  37733. /** Sets up the images to draw in various states.
  37734. @param resizeButtonNowToFitThisImage if true, the button will be immediately
  37735. resized to the same dimensions as the normal image
  37736. @param rescaleImagesWhenButtonSizeChanges if true, the image will be rescaled to fit the
  37737. button when the button's size changes
  37738. @param preserveImageProportions if true then any rescaling of the image to fit
  37739. the button will keep the image's x and y proportions
  37740. correct - i.e. it won't distort its shape, although
  37741. this might create gaps around the edges
  37742. @param normalImage the image to use when the button is in its normal state.
  37743. button no longer needs it.
  37744. @param imageOpacityWhenNormal the opacity to use when drawing the normal image.
  37745. @param overlayColourWhenNormal an overlay colour to use to fill the alpha channel of the
  37746. normal image - if this colour is transparent, no overlay
  37747. will be drawn. The overlay will be drawn over the top of the
  37748. image, so you can basically add a solid or semi-transparent
  37749. colour to the image to brighten or darken it
  37750. @param overImage the image to use when the mouse is over the button. If
  37751. you want to use the same image as was set in the normalImage
  37752. parameter, this value can be a null image.
  37753. @param imageOpacityWhenOver the opacity to use when drawing the image when the mouse
  37754. is over the button
  37755. @param overlayColourWhenOver an overlay colour to use to fill the alpha channel of the
  37756. image when the mouse is over - if this colour is transparent,
  37757. no overlay will be drawn
  37758. @param downImage an image to use when the button is pressed down. If set
  37759. to a null image, the 'over' image will be drawn instead (or the
  37760. normal image if there isn't an 'over' image either).
  37761. @param imageOpacityWhenDown the opacity to use when drawing the image when the button
  37762. is pressed
  37763. @param overlayColourWhenDown an overlay colour to use to fill the alpha channel of the
  37764. image when the button is pressed down - if this colour is
  37765. transparent, no overlay will be drawn
  37766. @param hitTestAlphaThreshold if set to zero, the mouse is considered to be over the button
  37767. whenever it's inside the button's bounding rectangle. If
  37768. set to values higher than 0, the mouse will only be
  37769. considered to be over the image when the value of the
  37770. image's alpha channel at that position is greater than
  37771. this level.
  37772. */
  37773. void setImages (bool resizeButtonNowToFitThisImage,
  37774. bool rescaleImagesWhenButtonSizeChanges,
  37775. bool preserveImageProportions,
  37776. const Image& normalImage,
  37777. float imageOpacityWhenNormal,
  37778. const Colour& overlayColourWhenNormal,
  37779. const Image& overImage,
  37780. float imageOpacityWhenOver,
  37781. const Colour& overlayColourWhenOver,
  37782. const Image& downImage,
  37783. float imageOpacityWhenDown,
  37784. const Colour& overlayColourWhenDown,
  37785. float hitTestAlphaThreshold = 0.0f);
  37786. /** Returns the currently set 'normal' image. */
  37787. Image getNormalImage() const;
  37788. /** Returns the image that's drawn when the mouse is over the button.
  37789. If a valid 'over' image has been set, this will return it; otherwise it'll
  37790. just return the normal image.
  37791. */
  37792. Image getOverImage() const;
  37793. /** Returns the image that's drawn when the button is held down.
  37794. If a valid 'down' image has been set, this will return it; otherwise it'll
  37795. return the 'over' image or normal image, depending on what's available.
  37796. */
  37797. Image getDownImage() const;
  37798. protected:
  37799. /** @internal */
  37800. bool hitTest (int x, int y);
  37801. /** @internal */
  37802. void paintButton (Graphics& g,
  37803. bool isMouseOverButton,
  37804. bool isButtonDown);
  37805. private:
  37806. bool scaleImageToFit, preserveProportions;
  37807. unsigned char alphaThreshold;
  37808. int imageX, imageY, imageW, imageH;
  37809. Image normalImage, overImage, downImage;
  37810. float normalOpacity, overOpacity, downOpacity;
  37811. Colour normalOverlay, overOverlay, downOverlay;
  37812. Image getCurrentImage() const;
  37813. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImageButton);
  37814. };
  37815. #endif // __JUCE_IMAGEBUTTON_JUCEHEADER__
  37816. /*** End of inlined file: juce_ImageButton.h ***/
  37817. #endif
  37818. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  37819. /*** Start of inlined file: juce_ShapeButton.h ***/
  37820. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  37821. #define __JUCE_SHAPEBUTTON_JUCEHEADER__
  37822. /**
  37823. A button that contains a filled shape.
  37824. @see Button, ImageButton, TextButton, ArrowButton
  37825. */
  37826. class JUCE_API ShapeButton : public Button
  37827. {
  37828. public:
  37829. /** Creates a ShapeButton.
  37830. @param name a name to give the component - see Component::setName()
  37831. @param normalColour the colour to fill the shape with when the mouse isn't over
  37832. @param overColour the colour to use when the mouse is over the shape
  37833. @param downColour the colour to use when the button is in the pressed-down state
  37834. */
  37835. ShapeButton (const String& name,
  37836. const Colour& normalColour,
  37837. const Colour& overColour,
  37838. const Colour& downColour);
  37839. /** Destructor. */
  37840. ~ShapeButton();
  37841. /** Sets the shape to use.
  37842. @param newShape the shape to use
  37843. @param resizeNowToFitThisShape if true, the button will be resized to fit the shape's bounds
  37844. @param maintainShapeProportions if true, the shape's proportions will be kept fixed when
  37845. the button is resized
  37846. @param hasDropShadow if true, the button will be given a drop-shadow effect
  37847. */
  37848. void setShape (const Path& newShape,
  37849. bool resizeNowToFitThisShape,
  37850. bool maintainShapeProportions,
  37851. bool hasDropShadow);
  37852. /** Set the colours to use for drawing the shape.
  37853. @param normalColour the colour to fill the shape with when the mouse isn't over
  37854. @param overColour the colour to use when the mouse is over the shape
  37855. @param downColour the colour to use when the button is in the pressed-down state
  37856. */
  37857. void setColours (const Colour& normalColour,
  37858. const Colour& overColour,
  37859. const Colour& downColour);
  37860. /** Sets up an outline to draw around the shape.
  37861. @param outlineColour the colour to use
  37862. @param outlineStrokeWidth the thickness of line to draw
  37863. */
  37864. void setOutline (const Colour& outlineColour,
  37865. float outlineStrokeWidth);
  37866. protected:
  37867. /** @internal */
  37868. void paintButton (Graphics& g,
  37869. bool isMouseOverButton,
  37870. bool isButtonDown);
  37871. private:
  37872. Colour normalColour, overColour, downColour, outlineColour;
  37873. DropShadowEffect shadow;
  37874. Path shape;
  37875. bool maintainShapeProportions;
  37876. float outlineWidth;
  37877. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ShapeButton);
  37878. };
  37879. #endif // __JUCE_SHAPEBUTTON_JUCEHEADER__
  37880. /*** End of inlined file: juce_ShapeButton.h ***/
  37881. #endif
  37882. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  37883. #endif
  37884. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  37885. /*** Start of inlined file: juce_ToggleButton.h ***/
  37886. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  37887. #define __JUCE_TOGGLEBUTTON_JUCEHEADER__
  37888. /**
  37889. A button that can be toggled on/off.
  37890. All buttons can be toggle buttons, but this lets you create one of the
  37891. standard ones which has a tick-box and a text label next to it.
  37892. @see Button, DrawableButton, TextButton
  37893. */
  37894. class JUCE_API ToggleButton : public Button
  37895. {
  37896. public:
  37897. /** Creates a ToggleButton.
  37898. @param buttonText the text to put in the button (the component's name is also
  37899. initially set to this string, but these can be changed later
  37900. using the setName() and setButtonText() methods)
  37901. */
  37902. explicit ToggleButton (const String& buttonText = String::empty);
  37903. /** Destructor. */
  37904. ~ToggleButton();
  37905. /** Resizes the button to fit neatly around its current text.
  37906. The button's height won't be affected, only its width.
  37907. */
  37908. void changeWidthToFitText();
  37909. /** A set of colour IDs to use to change the colour of various aspects of the button.
  37910. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37911. methods.
  37912. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37913. */
  37914. enum ColourIds
  37915. {
  37916. textColourId = 0x1006501 /**< The colour to use for the button's text. */
  37917. };
  37918. protected:
  37919. /** @internal */
  37920. void paintButton (Graphics& g,
  37921. bool isMouseOverButton,
  37922. bool isButtonDown);
  37923. /** @internal */
  37924. void colourChanged();
  37925. private:
  37926. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToggleButton);
  37927. };
  37928. #endif // __JUCE_TOGGLEBUTTON_JUCEHEADER__
  37929. /*** End of inlined file: juce_ToggleButton.h ***/
  37930. #endif
  37931. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  37932. /*** Start of inlined file: juce_ToolbarButton.h ***/
  37933. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  37934. #define __JUCE_TOOLBARBUTTON_JUCEHEADER__
  37935. /*** Start of inlined file: juce_ToolbarItemComponent.h ***/
  37936. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  37937. #define __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  37938. /*** Start of inlined file: juce_Toolbar.h ***/
  37939. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  37940. #define __JUCE_TOOLBAR_JUCEHEADER__
  37941. /*** Start of inlined file: juce_DragAndDropContainer.h ***/
  37942. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  37943. #define __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  37944. /*** Start of inlined file: juce_DragAndDropTarget.h ***/
  37945. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  37946. #define __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  37947. /**
  37948. Components derived from this class can have things dropped onto them by a DragAndDropContainer.
  37949. To create a component that can receive things drag-and-dropped by a DragAndDropContainer,
  37950. derive your component from this class, and make sure that it is somewhere inside a
  37951. DragAndDropContainer component.
  37952. Note: If all that you need to do is to respond to files being drag-and-dropped from
  37953. the operating system onto your component, you don't need any of these classes: instead
  37954. see the FileDragAndDropTarget class.
  37955. @see DragAndDropContainer, FileDragAndDropTarget
  37956. */
  37957. class JUCE_API DragAndDropTarget
  37958. {
  37959. public:
  37960. /** Destructor. */
  37961. virtual ~DragAndDropTarget() {}
  37962. /** Contains details about the source of a drag-and-drop operation.
  37963. The contents of this
  37964. */
  37965. class JUCE_API SourceDetails
  37966. {
  37967. public:
  37968. /** Creates a SourceDetails object from its various settings. */
  37969. SourceDetails (const var& description, Component* sourceComponent, const Point<int>& localPosition) noexcept;
  37970. /** A descriptor for the drag - this is set DragAndDropContainer::startDragging(). */
  37971. var description;
  37972. /** The component from the drag operation was started. */
  37973. WeakReference<Component> sourceComponent;
  37974. /** The local position of the mouse, relative to the target component.
  37975. Note that for calls such as isInterestedInDragSource(), this may be a null position.
  37976. */
  37977. Point<int> localPosition;
  37978. };
  37979. /** Callback to check whether this target is interested in the type of object being
  37980. dragged.
  37981. @param dragSourceDetails contains information about the source of the drag operation.
  37982. @returns true if this component wants to receive the other callbacks regarging this
  37983. type of object; if it returns false, no other callbacks will be made.
  37984. */
  37985. virtual bool isInterestedInDragSource (const SourceDetails& dragSourceDetails) = 0;
  37986. /** Callback to indicate that something is being dragged over this component.
  37987. This gets called when the user moves the mouse into this component while dragging
  37988. something.
  37989. Use this callback as a trigger to make your component repaint itself to give the
  37990. user feedback about whether the item can be dropped here or not.
  37991. @param dragSourceDetails contains information about the source of the drag operation.
  37992. @see itemDragExit
  37993. */
  37994. virtual void itemDragEnter (const SourceDetails& dragSourceDetails);
  37995. /** Callback to indicate that the user is dragging something over this component.
  37996. This gets called when the user moves the mouse over this component while dragging
  37997. something. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  37998. this lets you know what happens in-between.
  37999. @param dragSourceDetails contains information about the source of the drag operation.
  38000. */
  38001. virtual void itemDragMove (const SourceDetails& dragSourceDetails);
  38002. /** Callback to indicate that something has been dragged off the edge of this component.
  38003. This gets called when the user moves the mouse out of this component while dragging
  38004. something.
  38005. If you've used itemDragEnter() to repaint your component and give feedback, use this
  38006. as a signal to repaint it in its normal state.
  38007. @param dragSourceDetails contains information about the source of the drag operation.
  38008. @see itemDragEnter
  38009. */
  38010. virtual void itemDragExit (const SourceDetails& dragSourceDetails);
  38011. /** Callback to indicate that the user has dropped something onto this component.
  38012. When the user drops an item this get called, and you can use the description to
  38013. work out whether your object wants to deal with it or not.
  38014. Note that after this is called, the itemDragExit method may not be called, so you should
  38015. clean up in here if there's anything you need to do when the drag finishes.
  38016. @param dragSourceDetails contains information about the source of the drag operation.
  38017. */
  38018. virtual void itemDropped (const SourceDetails& dragSourceDetails) = 0;
  38019. /** Overriding this allows the target to tell the drag container whether to
  38020. draw the drag image while the cursor is over it.
  38021. By default it returns true, but if you return false, then the normal drag
  38022. image will not be shown when the cursor is over this target.
  38023. */
  38024. virtual bool shouldDrawDragImageWhenOver();
  38025. private:
  38026. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  38027. // The parameters for these methods have changed - please update your code!
  38028. virtual void isInterestedInDragSource (const String&, Component*) {}
  38029. virtual int itemDragEnter (const String&, Component*, int, int) { return 0; }
  38030. virtual int itemDragMove (const String&, Component*, int, int) { return 0; }
  38031. virtual int itemDragExit (const String&, Component*) { return 0; }
  38032. virtual int itemDropped (const String&, Component*, int, int) { return 0; }
  38033. #endif
  38034. };
  38035. #endif // __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  38036. /*** End of inlined file: juce_DragAndDropTarget.h ***/
  38037. /**
  38038. Enables drag-and-drop behaviour for a component and all its sub-components.
  38039. For a component to be able to make or receive drag-and-drop events, one of its parent
  38040. components must derive from this class. It's probably best for the top-level
  38041. component to implement it.
  38042. Then to start a drag operation, any sub-component can just call the startDragging()
  38043. method, and this object will take over, tracking the mouse and sending appropriate
  38044. callbacks to any child components derived from DragAndDropTarget which the mouse
  38045. moves over.
  38046. Note: If all that you need to do is to respond to files being drag-and-dropped from
  38047. the operating system onto your component, you don't need any of these classes: you can do this
  38048. simply by overriding Component::filesDropped().
  38049. @see DragAndDropTarget
  38050. */
  38051. class JUCE_API DragAndDropContainer
  38052. {
  38053. public:
  38054. /** Creates a DragAndDropContainer.
  38055. The object that derives from this class must also be a Component.
  38056. */
  38057. DragAndDropContainer();
  38058. /** Destructor. */
  38059. virtual ~DragAndDropContainer();
  38060. /** Begins a drag-and-drop operation.
  38061. This starts a drag-and-drop operation - call it when the user drags the
  38062. mouse in your drag-source component, and this object will track mouse
  38063. movements until the user lets go of the mouse button, and will send
  38064. appropriate messages to DragAndDropTarget objects that the mouse moves
  38065. over.
  38066. findParentDragContainerFor() is a handy method to call to find the
  38067. drag container to use for a component.
  38068. @param sourceDescription a string or value to use as the description of the thing being dragged -
  38069. this will be passed to the objects that might be dropped-onto so they can
  38070. decide whether they want to handle it
  38071. @param sourceComponent the component that is being dragged
  38072. @param dragImage the image to drag around underneath the mouse. If this is a null image,
  38073. a snapshot of the sourceComponent will be used instead.
  38074. @param allowDraggingToOtherJuceWindows if true, the dragged component will appear as a desktop
  38075. window, and can be dragged to DragAndDropTargets that are the
  38076. children of components other than this one.
  38077. @param imageOffsetFromMouse if an image has been passed-in, this specifies the offset
  38078. at which the image should be drawn from the mouse. If it isn't
  38079. specified, then the image will be centred around the mouse. If
  38080. an image hasn't been passed-in, this will be ignored.
  38081. */
  38082. void startDragging (const var& sourceDescription,
  38083. Component* sourceComponent,
  38084. const Image& dragImage = Image::null,
  38085. bool allowDraggingToOtherJuceWindows = false,
  38086. const Point<int>* imageOffsetFromMouse = nullptr);
  38087. /** Returns true if something is currently being dragged. */
  38088. bool isDragAndDropActive() const;
  38089. /** Returns the description of the thing that's currently being dragged.
  38090. If nothing's being dragged, this will return an empty string, otherwise it's the
  38091. string that was passed into startDragging().
  38092. @see startDragging
  38093. */
  38094. String getCurrentDragDescription() const;
  38095. /** Utility to find the DragAndDropContainer for a given Component.
  38096. This will search up this component's parent hierarchy looking for the first
  38097. parent component which is a DragAndDropContainer.
  38098. It's useful when a component wants to call startDragging but doesn't know
  38099. the DragAndDropContainer it should to use.
  38100. Obviously this may return 0 if it doesn't find a suitable component.
  38101. */
  38102. static DragAndDropContainer* findParentDragContainerFor (Component* childComponent);
  38103. /** This performs a synchronous drag-and-drop of a set of files to some external
  38104. application.
  38105. You can call this function in response to a mouseDrag callback, and it will
  38106. block, running its own internal message loop and tracking the mouse, while it
  38107. uses a native operating system drag-and-drop operation to move or copy some
  38108. files to another application.
  38109. @param files a list of filenames to drag
  38110. @param canMoveFiles if true, the app that receives the files is allowed to move the files to a new location
  38111. (if this is appropriate). If false, the receiver is expected to make a copy of them.
  38112. @returns true if the files were successfully dropped somewhere, or false if it
  38113. was interrupted
  38114. @see performExternalDragDropOfText
  38115. */
  38116. static bool performExternalDragDropOfFiles (const StringArray& files, bool canMoveFiles);
  38117. /** This performs a synchronous drag-and-drop of a block of text to some external
  38118. application.
  38119. You can call this function in response to a mouseDrag callback, and it will
  38120. block, running its own internal message loop and tracking the mouse, while it
  38121. uses a native operating system drag-and-drop operation to move or copy some
  38122. text to another application.
  38123. @param text the text to copy
  38124. @returns true if the text was successfully dropped somewhere, or false if it
  38125. was interrupted
  38126. @see performExternalDragDropOfFiles
  38127. */
  38128. static bool performExternalDragDropOfText (const String& text);
  38129. protected:
  38130. /** Override this if you want to be able to perform an external drag a set of files
  38131. when the user drags outside of this container component.
  38132. This method will be called when a drag operation moves outside the Juce-based window,
  38133. and if you want it to then perform a file drag-and-drop, add the filenames you want
  38134. to the array passed in, and return true.
  38135. @param sourceDetails information about the source of the drag operation
  38136. @param files on return, the filenames you want to drag
  38137. @param canMoveFiles on return, true if it's ok for the receiver to move the files; false if
  38138. it must make a copy of them (see the performExternalDragDropOfFiles() method)
  38139. @see performExternalDragDropOfFiles
  38140. */
  38141. virtual bool shouldDropFilesWhenDraggedExternally (const DragAndDropTarget::SourceDetails& sourceDetails,
  38142. StringArray& files, bool& canMoveFiles);
  38143. private:
  38144. friend class DragImageComponent;
  38145. ScopedPointer <Component> dragImageComponent;
  38146. String currentDragDesc;
  38147. JUCE_DEPRECATED (virtual bool shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)) { return false; }
  38148. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DragAndDropContainer);
  38149. };
  38150. #endif // __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  38151. /*** End of inlined file: juce_DragAndDropContainer.h ***/
  38152. class ToolbarItemComponent;
  38153. class ToolbarItemFactory;
  38154. /**
  38155. A toolbar component.
  38156. A toolbar contains a horizontal or vertical strip of ToolbarItemComponents,
  38157. and looks after their order and layout.
  38158. Items (icon buttons or other custom components) are added to a toolbar using a
  38159. ToolbarItemFactory - each type of item is given a unique ID number, and a
  38160. toolbar might contain more than one instance of a particular item type.
  38161. Toolbars can be interactively customised, allowing the user to drag the items
  38162. around, and to drag items onto or off the toolbar, using the ToolbarItemPalette
  38163. component as a source of new items.
  38164. @see ToolbarItemFactory, ToolbarItemComponent, ToolbarItemPalette
  38165. */
  38166. class JUCE_API Toolbar : public Component,
  38167. public DragAndDropContainer,
  38168. public DragAndDropTarget,
  38169. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  38170. {
  38171. public:
  38172. /** Creates an empty toolbar component.
  38173. To add some icons or other components to your toolbar, you'll need to
  38174. create a ToolbarItemFactory class that can create a suitable set of
  38175. ToolbarItemComponents.
  38176. @see ToolbarItemFactory, ToolbarItemComponents
  38177. */
  38178. Toolbar();
  38179. /** Destructor.
  38180. Any items on the bar will be deleted when the toolbar is deleted.
  38181. */
  38182. ~Toolbar();
  38183. /** Changes the bar's orientation.
  38184. @see isVertical
  38185. */
  38186. void setVertical (bool shouldBeVertical);
  38187. /** Returns true if the bar is set to be vertical, or false if it's horizontal.
  38188. You can change the bar's orientation with setVertical().
  38189. */
  38190. bool isVertical() const noexcept { return vertical; }
  38191. /** Returns the depth of the bar.
  38192. If the bar is horizontal, this will return its height; if it's vertical, it
  38193. will return its width.
  38194. @see getLength
  38195. */
  38196. int getThickness() const noexcept;
  38197. /** Returns the length of the bar.
  38198. If the bar is horizontal, this will return its width; if it's vertical, it
  38199. will return its height.
  38200. @see getThickness
  38201. */
  38202. int getLength() const noexcept;
  38203. /** Deletes all items from the bar.
  38204. */
  38205. void clear();
  38206. /** Adds an item to the toolbar.
  38207. The factory's ToolbarItemFactory::createItem() will be called by this method
  38208. to create the component that will actually be added to the bar.
  38209. The new item will be inserted at the specified index (if the index is -1, it
  38210. will be added to the right-hand or bottom end of the bar).
  38211. Once added, the component will be automatically deleted by this object when it
  38212. is no longer needed.
  38213. @see ToolbarItemFactory
  38214. */
  38215. void addItem (ToolbarItemFactory& factory,
  38216. int itemId,
  38217. int insertIndex = -1);
  38218. /** Deletes one of the items from the bar.
  38219. */
  38220. void removeToolbarItem (int itemIndex);
  38221. /** Returns the number of items currently on the toolbar.
  38222. @see getItemId, getItemComponent
  38223. */
  38224. int getNumItems() const noexcept;
  38225. /** Returns the ID of the item with the given index.
  38226. If the index is less than zero or greater than the number of items,
  38227. this will return 0.
  38228. @see getNumItems
  38229. */
  38230. int getItemId (int itemIndex) const noexcept;
  38231. /** Returns the component being used for the item with the given index.
  38232. If the index is less than zero or greater than the number of items,
  38233. this will return 0.
  38234. @see getNumItems
  38235. */
  38236. ToolbarItemComponent* getItemComponent (int itemIndex) const noexcept;
  38237. /** Clears this toolbar and adds to it the default set of items that the specified
  38238. factory creates.
  38239. @see ToolbarItemFactory::getDefaultItemSet
  38240. */
  38241. void addDefaultItems (ToolbarItemFactory& factoryToUse);
  38242. /** Options for the way items should be displayed.
  38243. @see setStyle, getStyle
  38244. */
  38245. enum ToolbarItemStyle
  38246. {
  38247. iconsOnly, /**< Means that the toolbar should just contain icons. */
  38248. iconsWithText, /**< Means that the toolbar should have text labels under each icon. */
  38249. textOnly /**< Means that the toolbar only display text labels for each item. */
  38250. };
  38251. /** Returns the toolbar's current style.
  38252. @see ToolbarItemStyle, setStyle
  38253. */
  38254. ToolbarItemStyle getStyle() const noexcept { return toolbarStyle; }
  38255. /** Changes the toolbar's current style.
  38256. @see ToolbarItemStyle, getStyle, ToolbarItemComponent::setStyle
  38257. */
  38258. void setStyle (const ToolbarItemStyle& newStyle);
  38259. /** Flags used by the showCustomisationDialog() method. */
  38260. enum CustomisationFlags
  38261. {
  38262. allowIconsOnlyChoice = 1, /**< If this flag is specified, the customisation dialog can
  38263. show the "icons only" option on its choice of toolbar styles. */
  38264. allowIconsWithTextChoice = 2, /**< If this flag is specified, the customisation dialog can
  38265. show the "icons with text" option on its choice of toolbar styles. */
  38266. allowTextOnlyChoice = 4, /**< If this flag is specified, the customisation dialog can
  38267. show the "text only" option on its choice of toolbar styles. */
  38268. showResetToDefaultsButton = 8, /**< If this flag is specified, the customisation dialog can
  38269. show a button to reset the toolbar to its default set of items. */
  38270. allCustomisationOptionsEnabled = (allowIconsOnlyChoice | allowIconsWithTextChoice | allowTextOnlyChoice | showResetToDefaultsButton)
  38271. };
  38272. /** Pops up a modal dialog box that allows this toolbar to be customised by the user.
  38273. The dialog contains a ToolbarItemPalette and various controls for editing other
  38274. aspects of the toolbar. This method will block and run the dialog box modally,
  38275. returning when the user closes it.
  38276. The factory is used to determine the set of items that will be shown on the
  38277. palette.
  38278. The optionFlags parameter is a bitwise-or of values from the CustomisationFlags
  38279. enum.
  38280. @see ToolbarItemPalette
  38281. */
  38282. void showCustomisationDialog (ToolbarItemFactory& factory,
  38283. int optionFlags = allCustomisationOptionsEnabled);
  38284. /** Turns on or off the toolbar's editing mode, in which its items can be
  38285. rearranged by the user.
  38286. (In most cases it's easier just to use showCustomisationDialog() instead of
  38287. trying to enable editing directly).
  38288. @see ToolbarItemPalette
  38289. */
  38290. void setEditingActive (bool editingEnabled);
  38291. /** A set of colour IDs to use to change the colour of various aspects of the toolbar.
  38292. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38293. methods.
  38294. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38295. */
  38296. enum ColourIds
  38297. {
  38298. backgroundColourId = 0x1003200, /**< A colour to use to fill the toolbar's background. For
  38299. more control over this, override LookAndFeel::paintToolbarBackground(). */
  38300. separatorColourId = 0x1003210, /**< A colour to use to draw the separator lines. */
  38301. buttonMouseOverBackgroundColourId = 0x1003220, /**< A colour used to paint the background of buttons when the mouse is
  38302. over them. */
  38303. buttonMouseDownBackgroundColourId = 0x1003230, /**< A colour used to paint the background of buttons when the mouse is
  38304. held down on them. */
  38305. labelTextColourId = 0x1003240, /**< A colour to use for drawing the text under buttons
  38306. when the style is set to iconsWithText or textOnly. */
  38307. editingModeOutlineColourId = 0x1003250 /**< A colour to use for an outline around buttons when
  38308. the customisation dialog is active and the mouse moves over them. */
  38309. };
  38310. /** Returns a string that represents the toolbar's current set of items.
  38311. This lets you later restore the same item layout using restoreFromString().
  38312. @see restoreFromString
  38313. */
  38314. String toString() const;
  38315. /** Restores a set of items that was previously stored in a string by the toString()
  38316. method.
  38317. The factory object is used to create any item components that are needed.
  38318. @see toString
  38319. */
  38320. bool restoreFromString (ToolbarItemFactory& factoryToUse,
  38321. const String& savedVersion);
  38322. /** @internal */
  38323. void paint (Graphics& g);
  38324. /** @internal */
  38325. void resized();
  38326. /** @internal */
  38327. void buttonClicked (Button*);
  38328. /** @internal */
  38329. void mouseDown (const MouseEvent&);
  38330. /** @internal */
  38331. bool isInterestedInDragSource (const SourceDetails&);
  38332. /** @internal */
  38333. void itemDragMove (const SourceDetails&);
  38334. /** @internal */
  38335. void itemDragExit (const SourceDetails&);
  38336. /** @internal */
  38337. void itemDropped (const SourceDetails&);
  38338. /** @internal */
  38339. void updateAllItemPositions (bool animate);
  38340. /** @internal */
  38341. static ToolbarItemComponent* createItem (ToolbarItemFactory&, int itemId);
  38342. private:
  38343. ScopedPointer<Button> missingItemsButton;
  38344. bool vertical, isEditingActive;
  38345. ToolbarItemStyle toolbarStyle;
  38346. class MissingItemsComponent;
  38347. friend class MissingItemsComponent;
  38348. OwnedArray <ToolbarItemComponent> items;
  38349. friend class ItemDragAndDropOverlayComponent;
  38350. static const char* const toolbarDragDescriptor;
  38351. void addItemInternal (ToolbarItemFactory& factory, int itemId, int insertIndex);
  38352. ToolbarItemComponent* getNextActiveComponent (int index, int delta) const;
  38353. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Toolbar);
  38354. };
  38355. #endif // __JUCE_TOOLBAR_JUCEHEADER__
  38356. /*** End of inlined file: juce_Toolbar.h ***/
  38357. class ItemDragAndDropOverlayComponent;
  38358. /**
  38359. A component that can be used as one of the items in a Toolbar.
  38360. Each of the items on a toolbar must be a component derived from ToolbarItemComponent,
  38361. and these objects are always created by a ToolbarItemFactory - see the ToolbarItemFactory
  38362. class for further info about creating them.
  38363. The ToolbarItemComponent class is actually a button, but can be used to hold non-button
  38364. components too. To do this, set the value of isBeingUsedAsAButton to false when
  38365. calling the constructor, and override contentAreaChanged(), in which you can position
  38366. any sub-components you need to add.
  38367. To add basic buttons without writing a special subclass, have a look at the
  38368. ToolbarButton class.
  38369. @see ToolbarButton, Toolbar, ToolbarItemFactory
  38370. */
  38371. class JUCE_API ToolbarItemComponent : public Button
  38372. {
  38373. public:
  38374. /** Constructor.
  38375. @param itemId the ID of the type of toolbar item which this represents
  38376. @param labelText the text to display if the toolbar's style is set to
  38377. Toolbar::iconsWithText or Toolbar::textOnly
  38378. @param isBeingUsedAsAButton set this to false if you don't want the button
  38379. to draw itself with button over/down states when the mouse
  38380. moves over it or clicks
  38381. */
  38382. ToolbarItemComponent (int itemId,
  38383. const String& labelText,
  38384. bool isBeingUsedAsAButton);
  38385. /** Destructor. */
  38386. ~ToolbarItemComponent();
  38387. /** Returns the item type ID that this component represents.
  38388. This value is in the constructor.
  38389. */
  38390. int getItemId() const noexcept { return itemId; }
  38391. /** Returns the toolbar that contains this component, or 0 if it's not currently
  38392. inside one.
  38393. */
  38394. Toolbar* getToolbar() const;
  38395. /** Returns true if this component is currently inside a toolbar which is vertical.
  38396. @see Toolbar::isVertical
  38397. */
  38398. bool isToolbarVertical() const;
  38399. /** Returns the current style setting of this item.
  38400. Styles are listed in the Toolbar::ToolbarItemStyle enum.
  38401. @see setStyle, Toolbar::getStyle
  38402. */
  38403. Toolbar::ToolbarItemStyle getStyle() const noexcept { return toolbarStyle; }
  38404. /** Changes the current style setting of this item.
  38405. Styles are listed in the Toolbar::ToolbarItemStyle enum, and are automatically updated
  38406. by the toolbar that holds this item.
  38407. @see setStyle, Toolbar::setStyle
  38408. */
  38409. virtual void setStyle (const Toolbar::ToolbarItemStyle& newStyle);
  38410. /** Returns the area of the component that should be used to display the button image or
  38411. other contents of the item.
  38412. This content area may change when the item's style changes, and may leave a space around the
  38413. edge of the component where the text label can be shown.
  38414. @see contentAreaChanged
  38415. */
  38416. const Rectangle<int> getContentArea() const noexcept { return contentArea; }
  38417. /** This method must return the size criteria for this item, based on a given toolbar
  38418. size and orientation.
  38419. The preferredSize, minSize and maxSize values must all be set by your implementation
  38420. method. If the toolbar is horizontal, these will be the width of the item; for a vertical
  38421. toolbar, they refer to the item's height.
  38422. The preferredSize is the size that the component would like to be, and this must be
  38423. between the min and max sizes. For a fixed-size item, simply set all three variables to
  38424. the same value.
  38425. The toolbarThickness parameter tells you the depth of the toolbar - the same as calling
  38426. Toolbar::getThickness().
  38427. The isToolbarVertical parameter tells you whether the bar is oriented horizontally or
  38428. vertically.
  38429. */
  38430. virtual bool getToolbarItemSizes (int toolbarThickness,
  38431. bool isToolbarVertical,
  38432. int& preferredSize,
  38433. int& minSize,
  38434. int& maxSize) = 0;
  38435. /** Your subclass should use this method to draw its content area.
  38436. The graphics object that is passed-in will have been clipped and had its origin
  38437. moved to fit the content area as specified get getContentArea(). The width and height
  38438. parameters are the width and height of the content area.
  38439. If the component you're writing isn't a button, you can just do nothing in this method.
  38440. */
  38441. virtual void paintButtonArea (Graphics& g,
  38442. int width, int height,
  38443. bool isMouseOver, bool isMouseDown) = 0;
  38444. /** Callback to indicate that the content area of this item has changed.
  38445. This might be because the component was resized, or because the style changed and
  38446. the space needed for the text label is different.
  38447. See getContentArea() for a description of what the area is.
  38448. */
  38449. virtual void contentAreaChanged (const Rectangle<int>& newBounds) = 0;
  38450. /** Editing modes.
  38451. These are used by setEditingMode(), but will be rarely needed in user code.
  38452. */
  38453. enum ToolbarEditingMode
  38454. {
  38455. normalMode = 0, /**< Means that the component is active, inside a toolbar. */
  38456. editableOnToolbar, /**< Means that the component is on a toolbar, but the toolbar is in
  38457. customisation mode, and the items can be dragged around. */
  38458. editableOnPalette /**< Means that the component is on an new-item palette, so it can be
  38459. dragged onto a toolbar to add it to that bar.*/
  38460. };
  38461. /** Changes the editing mode of this component.
  38462. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  38463. and is unlikely to be of much use in end-user-code.
  38464. */
  38465. void setEditingMode (const ToolbarEditingMode newMode);
  38466. /** Returns the current editing mode of this component.
  38467. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  38468. and is unlikely to be of much use in end-user-code.
  38469. */
  38470. ToolbarEditingMode getEditingMode() const noexcept { return mode; }
  38471. /** @internal */
  38472. void paintButton (Graphics& g, bool isMouseOver, bool isMouseDown);
  38473. /** @internal */
  38474. void resized();
  38475. private:
  38476. friend class Toolbar;
  38477. friend class ItemDragAndDropOverlayComponent;
  38478. const int itemId;
  38479. ToolbarEditingMode mode;
  38480. Toolbar::ToolbarItemStyle toolbarStyle;
  38481. ScopedPointer <Component> overlayComp;
  38482. int dragOffsetX, dragOffsetY;
  38483. bool isActive, isBeingDragged, isBeingUsedAsAButton;
  38484. Rectangle<int> contentArea;
  38485. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarItemComponent);
  38486. };
  38487. #endif // __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  38488. /*** End of inlined file: juce_ToolbarItemComponent.h ***/
  38489. /**
  38490. A type of button designed to go on a toolbar.
  38491. This simple button can have two Drawable objects specified - one for normal
  38492. use and another one (optionally) for the button's "on" state if it's a
  38493. toggle button.
  38494. @see Toolbar, ToolbarItemFactory, ToolbarItemComponent, Drawable, Button
  38495. */
  38496. class JUCE_API ToolbarButton : public ToolbarItemComponent
  38497. {
  38498. public:
  38499. /** Creates a ToolbarButton.
  38500. @param itemId the ID for this toolbar item type. This is passed through to the
  38501. ToolbarItemComponent constructor
  38502. @param labelText the text to display on the button (if the toolbar is using a style
  38503. that shows text labels). This is passed through to the
  38504. ToolbarItemComponent constructor
  38505. @param normalImage a drawable object that the button should use as its icon. The object
  38506. that is passed-in here will be kept by this object and will be
  38507. deleted when no longer needed or when this button is deleted.
  38508. @param toggledOnImage a drawable object that the button can use as its icon if the button
  38509. is in a toggled-on state (see the Button::getToggleState() method). If
  38510. 0 is passed-in here, then the normal image will be used instead, regardless
  38511. of the toggle state. The object that is passed-in here will be kept by
  38512. this object and will be deleted when no longer needed or when this button
  38513. is deleted.
  38514. */
  38515. ToolbarButton (int itemId,
  38516. const String& labelText,
  38517. Drawable* normalImage,
  38518. Drawable* toggledOnImage);
  38519. /** Destructor. */
  38520. ~ToolbarButton();
  38521. /** @internal */
  38522. bool getToolbarItemSizes (int toolbarDepth, bool isToolbarVertical, int& preferredSize,
  38523. int& minSize, int& maxSize);
  38524. /** @internal */
  38525. void paintButtonArea (Graphics& g, int width, int height, bool isMouseOver, bool isMouseDown);
  38526. /** @internal */
  38527. void contentAreaChanged (const Rectangle<int>& newBounds);
  38528. /** @internal */
  38529. void buttonStateChanged();
  38530. /** @internal */
  38531. void resized();
  38532. /** @internal */
  38533. void enablementChanged();
  38534. private:
  38535. ScopedPointer<Drawable> normalImage, toggledOnImage;
  38536. Drawable* currentImage;
  38537. void updateDrawable();
  38538. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarButton);
  38539. };
  38540. #endif // __JUCE_TOOLBARBUTTON_JUCEHEADER__
  38541. /*** End of inlined file: juce_ToolbarButton.h ***/
  38542. #endif
  38543. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  38544. /*** Start of inlined file: juce_CodeDocument.h ***/
  38545. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  38546. #define __JUCE_CODEDOCUMENT_JUCEHEADER__
  38547. class CodeDocumentLine;
  38548. /**
  38549. A class for storing and manipulating a source code file.
  38550. When using a CodeEditorComponent, it takes one of these as its source object.
  38551. The CodeDocument stores its content as an array of lines, which makes it
  38552. quick to insert and delete.
  38553. @see CodeEditorComponent
  38554. */
  38555. class JUCE_API CodeDocument
  38556. {
  38557. public:
  38558. /** Creates a new, empty document.
  38559. */
  38560. CodeDocument();
  38561. /** Destructor. */
  38562. ~CodeDocument();
  38563. /** A position in a code document.
  38564. Using this class you can find a position in a code document and quickly get its
  38565. character position, line, and index. By calling setPositionMaintained (true), the
  38566. position is automatically updated when text is inserted or deleted in the document,
  38567. so that it maintains its original place in the text.
  38568. */
  38569. class JUCE_API Position
  38570. {
  38571. public:
  38572. /** Creates an uninitialised postion.
  38573. Don't attempt to call any methods on this until you've given it an owner document
  38574. to refer to!
  38575. */
  38576. Position() noexcept;
  38577. /** Creates a position based on a line and index in a document.
  38578. Note that this index is NOT the column number, it's the number of characters from the
  38579. start of the line. The "column" number isn't quite the same, because if the line
  38580. contains any tab characters, the relationship of the index to its visual column depends on
  38581. the number of spaces per tab being used!
  38582. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  38583. they will be adjusted to keep them within its limits.
  38584. */
  38585. Position (const CodeDocument* ownerDocument,
  38586. int line, int indexInLine) noexcept;
  38587. /** Creates a position based on a character index in a document.
  38588. This position is placed at the specified number of characters from the start of the
  38589. document. The line and column are auto-calculated.
  38590. If the position is beyond the range of the document, it'll be adjusted to keep it
  38591. inside.
  38592. */
  38593. Position (const CodeDocument* ownerDocument,
  38594. int charactersFromStartOfDocument) noexcept;
  38595. /** Creates a copy of another position.
  38596. This will copy the position, but the new object will not be set to maintain its position,
  38597. even if the source object was set to do so.
  38598. */
  38599. Position (const Position& other) noexcept;
  38600. /** Destructor. */
  38601. ~Position();
  38602. Position& operator= (const Position& other);
  38603. bool operator== (const Position& other) const noexcept;
  38604. bool operator!= (const Position& other) const noexcept;
  38605. /** Points this object at a new position within the document.
  38606. If the position is beyond the range of the document, it'll be adjusted to keep it
  38607. inside.
  38608. @see getPosition, setLineAndIndex
  38609. */
  38610. void setPosition (int charactersFromStartOfDocument);
  38611. /** Returns the position as the number of characters from the start of the document.
  38612. @see setPosition, getLineNumber, getIndexInLine
  38613. */
  38614. int getPosition() const noexcept { return characterPos; }
  38615. /** Moves the position to a new line and index within the line.
  38616. Note that the index is NOT the column at which the position appears in an editor.
  38617. If the line contains any tab characters, the relationship of the index to its
  38618. visual position depends on the number of spaces per tab being used!
  38619. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  38620. they will be adjusted to keep them within its limits.
  38621. */
  38622. void setLineAndIndex (int newLine, int newIndexInLine);
  38623. /** Returns the line number of this position.
  38624. The first line in the document is numbered zero, not one!
  38625. */
  38626. int getLineNumber() const noexcept { return line; }
  38627. /** Returns the number of characters from the start of the line.
  38628. Note that this value is NOT the column at which the position appears in an editor.
  38629. If the line contains any tab characters, the relationship of the index to its
  38630. visual position depends on the number of spaces per tab being used!
  38631. */
  38632. int getIndexInLine() const noexcept { return indexInLine; }
  38633. /** Allows the position to be automatically updated when the document changes.
  38634. If this is set to true, the positon will register with its document so that
  38635. when the document has text inserted or deleted, this position will be automatically
  38636. moved to keep it at the same position in the text.
  38637. */
  38638. void setPositionMaintained (bool isMaintained);
  38639. /** Moves the position forwards or backwards by the specified number of characters.
  38640. @see movedBy
  38641. */
  38642. void moveBy (int characterDelta);
  38643. /** Returns a position which is the same as this one, moved by the specified number of
  38644. characters.
  38645. @see moveBy
  38646. */
  38647. const Position movedBy (int characterDelta) const;
  38648. /** Returns a position which is the same as this one, moved up or down by the specified
  38649. number of lines.
  38650. @see movedBy
  38651. */
  38652. const Position movedByLines (int deltaLines) const;
  38653. /** Returns the character in the document at this position.
  38654. @see getLineText
  38655. */
  38656. const juce_wchar getCharacter() const;
  38657. /** Returns the line from the document that this position is within.
  38658. @see getCharacter, getLineNumber
  38659. */
  38660. String getLineText() const;
  38661. private:
  38662. CodeDocument* owner;
  38663. int characterPos, line, indexInLine;
  38664. bool positionMaintained;
  38665. };
  38666. /** Returns the full text of the document. */
  38667. String getAllContent() const;
  38668. /** Returns a section of the document's text. */
  38669. String getTextBetween (const Position& start, const Position& end) const;
  38670. /** Returns a line from the document. */
  38671. String getLine (int lineIndex) const noexcept;
  38672. /** Returns the number of characters in the document. */
  38673. int getNumCharacters() const noexcept;
  38674. /** Returns the number of lines in the document. */
  38675. int getNumLines() const noexcept { return lines.size(); }
  38676. /** Returns the number of characters in the longest line of the document. */
  38677. int getMaximumLineLength() noexcept;
  38678. /** Deletes a section of the text.
  38679. This operation is undoable.
  38680. */
  38681. void deleteSection (const Position& startPosition, const Position& endPosition);
  38682. /** Inserts some text into the document at a given position.
  38683. This operation is undoable.
  38684. */
  38685. void insertText (const Position& position, const String& text);
  38686. /** Clears the document and replaces it with some new text.
  38687. This operation is undoable - if you're trying to completely reset the document, you
  38688. might want to also call clearUndoHistory() and setSavePoint() after using this method.
  38689. */
  38690. void replaceAllContent (const String& newContent);
  38691. /** Replaces the editor's contents with the contents of a stream.
  38692. This will also reset the undo history and save point marker.
  38693. */
  38694. bool loadFromStream (InputStream& stream);
  38695. /** Writes the editor's current contents to a stream. */
  38696. bool writeToStream (OutputStream& stream);
  38697. /** Returns the preferred new-line characters for the document.
  38698. This will be either "\n", "\r\n", or (rarely) "\r".
  38699. @see setNewLineCharacters
  38700. */
  38701. String getNewLineCharacters() const noexcept { return newLineChars; }
  38702. /** Sets the new-line characters that the document should use.
  38703. The string must be either "\n", "\r\n", or (rarely) "\r".
  38704. @see getNewLineCharacters
  38705. */
  38706. void setNewLineCharacters (const String& newLine) noexcept;
  38707. /** Begins a new undo transaction.
  38708. The document itself will not call this internally, so relies on whatever is using the
  38709. document to periodically call this to break up the undo sequence into sensible chunks.
  38710. @see UndoManager::beginNewTransaction
  38711. */
  38712. void newTransaction();
  38713. /** Undo the last operation.
  38714. @see UndoManager::undo
  38715. */
  38716. void undo();
  38717. /** Redo the last operation.
  38718. @see UndoManager::redo
  38719. */
  38720. void redo();
  38721. /** Clears the undo history.
  38722. @see UndoManager::clearUndoHistory
  38723. */
  38724. void clearUndoHistory();
  38725. /** Returns the document's UndoManager */
  38726. UndoManager& getUndoManager() noexcept { return undoManager; }
  38727. /** Makes a note that the document's current state matches the one that is saved.
  38728. After this has been called, hasChangedSinceSavePoint() will return false until
  38729. the document has been altered, and then it'll start returning true. If the document is
  38730. altered, but then undone until it gets back to this state, hasChangedSinceSavePoint()
  38731. will again return false.
  38732. @see hasChangedSinceSavePoint
  38733. */
  38734. void setSavePoint() noexcept;
  38735. /** Returns true if the state of the document differs from the state it was in when
  38736. setSavePoint() was last called.
  38737. @see setSavePoint
  38738. */
  38739. bool hasChangedSinceSavePoint() const noexcept;
  38740. /** Searches for a word-break. */
  38741. const Position findWordBreakAfter (const Position& position) const noexcept;
  38742. /** Searches for a word-break. */
  38743. const Position findWordBreakBefore (const Position& position) const noexcept;
  38744. /** An object that receives callbacks from the CodeDocument when its text changes.
  38745. @see CodeDocument::addListener, CodeDocument::removeListener
  38746. */
  38747. class JUCE_API Listener
  38748. {
  38749. public:
  38750. Listener() {}
  38751. virtual ~Listener() {}
  38752. /** Called by a CodeDocument when it is altered.
  38753. */
  38754. virtual void codeDocumentChanged (const Position& affectedTextStart,
  38755. const Position& affectedTextEnd) = 0;
  38756. };
  38757. /** Registers a listener object to receive callbacks when the document changes.
  38758. If the listener is already registered, this method has no effect.
  38759. @see removeListener
  38760. */
  38761. void addListener (Listener* listener) noexcept;
  38762. /** Deregisters a listener.
  38763. @see addListener
  38764. */
  38765. void removeListener (Listener* listener) noexcept;
  38766. /** Iterates the text in a CodeDocument.
  38767. This class lets you read characters from a CodeDocument. It's designed to be used
  38768. by a SyntaxAnalyser object.
  38769. @see CodeDocument, SyntaxAnalyser
  38770. */
  38771. class JUCE_API Iterator
  38772. {
  38773. public:
  38774. Iterator (CodeDocument* document);
  38775. Iterator (const Iterator& other);
  38776. Iterator& operator= (const Iterator& other) noexcept;
  38777. ~Iterator() noexcept;
  38778. /** Reads the next character and returns it.
  38779. @see peekNextChar
  38780. */
  38781. juce_wchar nextChar();
  38782. /** Reads the next character without advancing the current position. */
  38783. juce_wchar peekNextChar() const;
  38784. /** Advances the position by one character. */
  38785. void skip();
  38786. /** Returns the position of the next character as its position within the
  38787. whole document.
  38788. */
  38789. int getPosition() const noexcept { return position; }
  38790. /** Skips over any whitespace characters until the next character is non-whitespace. */
  38791. void skipWhitespace();
  38792. /** Skips forward until the next character will be the first character on the next line */
  38793. void skipToEndOfLine();
  38794. /** Returns the line number of the next character. */
  38795. int getLine() const noexcept { return line; }
  38796. /** Returns true if the iterator has reached the end of the document. */
  38797. bool isEOF() const noexcept;
  38798. private:
  38799. CodeDocument* document;
  38800. mutable String::CharPointerType charPointer;
  38801. int line, position;
  38802. };
  38803. private:
  38804. friend class CodeDocumentInsertAction;
  38805. friend class CodeDocumentDeleteAction;
  38806. friend class Iterator;
  38807. friend class Position;
  38808. OwnedArray <CodeDocumentLine> lines;
  38809. Array <Position*> positionsToMaintain;
  38810. UndoManager undoManager;
  38811. int currentActionIndex, indexOfSavedState;
  38812. int maximumLineLength;
  38813. ListenerList <Listener> listeners;
  38814. String newLineChars;
  38815. void sendListenerChangeMessage (int startLine, int endLine);
  38816. void insert (const String& text, int insertPos, bool undoable);
  38817. void remove (int startPos, int endPos, bool undoable);
  38818. void checkLastLineStatus();
  38819. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CodeDocument);
  38820. };
  38821. #endif // __JUCE_CODEDOCUMENT_JUCEHEADER__
  38822. /*** End of inlined file: juce_CodeDocument.h ***/
  38823. #endif
  38824. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  38825. /*** Start of inlined file: juce_CodeEditorComponent.h ***/
  38826. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  38827. #define __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  38828. /*** Start of inlined file: juce_TextInputTarget.h ***/
  38829. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  38830. #define __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  38831. /**
  38832. An abstract base class which can be implemented by components that function as
  38833. text editors.
  38834. This class allows different types of text editor component to provide a uniform
  38835. interface, which can be used by things like OS-specific input methods, on-screen
  38836. keyboards, etc.
  38837. */
  38838. class JUCE_API TextInputTarget
  38839. {
  38840. public:
  38841. /** */
  38842. TextInputTarget() {}
  38843. /** Destructor. */
  38844. virtual ~TextInputTarget() {}
  38845. /** Returns true if this input target is currently accepting input.
  38846. For example, a text editor might return false if it's in read-only mode.
  38847. */
  38848. virtual bool isTextInputActive() const = 0;
  38849. /** Returns the extents of the selected text region, or an empty range if
  38850. nothing is selected,
  38851. */
  38852. virtual const Range<int> getHighlightedRegion() const = 0;
  38853. /** Sets the currently-selected text region. */
  38854. virtual void setHighlightedRegion (const Range<int>& newRange) = 0;
  38855. /** Sets a number of temporarily underlined sections.
  38856. This is needed by MS Windows input method UI.
  38857. */
  38858. virtual void setTemporaryUnderlining (const Array <Range<int> >& underlinedRegions) = 0;
  38859. /** Returns a specified sub-section of the text. */
  38860. virtual const String getTextInRange (const Range<int>& range) const = 0;
  38861. /** Inserts some text, overwriting the selected text region, if there is one. */
  38862. virtual void insertTextAtCaret (const String& textToInsert) = 0;
  38863. /** Returns the position of the caret, relative to the component's origin. */
  38864. virtual const Rectangle<int> getCaretRectangle() = 0;
  38865. };
  38866. #endif // __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  38867. /*** End of inlined file: juce_TextInputTarget.h ***/
  38868. /*** Start of inlined file: juce_CaretComponent.h ***/
  38869. #ifndef __JUCE_CARETCOMPONENT_JUCEHEADER__
  38870. #define __JUCE_CARETCOMPONENT_JUCEHEADER__
  38871. /**
  38872. */
  38873. class JUCE_API CaretComponent : public Component,
  38874. public Timer
  38875. {
  38876. public:
  38877. /** Creates the caret component.
  38878. The keyFocusOwner is an optional component which the caret will check, making
  38879. itself visible only when the keyFocusOwner has keyboard focus.
  38880. */
  38881. CaretComponent (Component* keyFocusOwner);
  38882. /** Destructor. */
  38883. ~CaretComponent();
  38884. /** Sets the caret's position to place it next to the given character.
  38885. The area is the rectangle containing the entire character that the caret is
  38886. positioned on, so by default a vertical-line caret may choose to just show itself
  38887. at the left of this area. You can override this method to customise its size.
  38888. This method will also force the caret to reset its timer and become visible (if
  38889. appropriate), so that as it moves, you can see where it is.
  38890. */
  38891. virtual void setCaretPosition (const Rectangle<int>& characterArea);
  38892. /** A set of colour IDs to use to change the colour of various aspects of the caret.
  38893. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38894. methods.
  38895. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38896. */
  38897. enum ColourIds
  38898. {
  38899. caretColourId = 0x1000204, /**< The colour with which to draw the caret. */
  38900. };
  38901. /** @internal */
  38902. void paint (Graphics& g);
  38903. /** @internal */
  38904. void timerCallback();
  38905. private:
  38906. Component* owner;
  38907. bool shouldBeShown() const;
  38908. JUCE_DECLARE_NON_COPYABLE (CaretComponent);
  38909. };
  38910. #endif // __JUCE_CARETCOMPONENT_JUCEHEADER__
  38911. /*** End of inlined file: juce_CaretComponent.h ***/
  38912. /*** Start of inlined file: juce_CodeTokeniser.h ***/
  38913. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  38914. #define __JUCE_CODETOKENISER_JUCEHEADER__
  38915. /**
  38916. A base class for tokenising code so that the syntax can be displayed in a
  38917. code editor.
  38918. @see CodeDocument, CodeEditorComponent
  38919. */
  38920. class JUCE_API CodeTokeniser
  38921. {
  38922. public:
  38923. CodeTokeniser() {}
  38924. virtual ~CodeTokeniser() {}
  38925. /** Reads the next token from the source and returns its token type.
  38926. This must leave the source pointing to the first character in the
  38927. next token.
  38928. */
  38929. virtual int readNextToken (CodeDocument::Iterator& source) = 0;
  38930. /** Returns a list of the names of the token types this analyser uses.
  38931. The index in this list must match the token type numbers that are
  38932. returned by readNextToken().
  38933. */
  38934. virtual StringArray getTokenTypes() = 0;
  38935. /** Returns a suggested syntax highlighting colour for a specified
  38936. token type.
  38937. */
  38938. virtual const Colour getDefaultColour (int tokenType) = 0;
  38939. private:
  38940. JUCE_LEAK_DETECTOR (CodeTokeniser);
  38941. };
  38942. #endif // __JUCE_CODETOKENISER_JUCEHEADER__
  38943. /*** End of inlined file: juce_CodeTokeniser.h ***/
  38944. /**
  38945. A text editor component designed specifically for source code.
  38946. This is designed to handle syntax highlighting and fast editing of very large
  38947. files.
  38948. */
  38949. class JUCE_API CodeEditorComponent : public Component,
  38950. public TextInputTarget,
  38951. public Timer,
  38952. public ScrollBar::Listener,
  38953. public CodeDocument::Listener,
  38954. public AsyncUpdater
  38955. {
  38956. public:
  38957. /** Creates an editor for a document.
  38958. The tokeniser object is optional - pass 0 to disable syntax highlighting.
  38959. The object that you pass in is not owned or deleted by the editor - you must
  38960. make sure that it doesn't get deleted while this component is still using it.
  38961. @see CodeDocument
  38962. */
  38963. CodeEditorComponent (CodeDocument& document,
  38964. CodeTokeniser* codeTokeniser);
  38965. /** Destructor. */
  38966. ~CodeEditorComponent();
  38967. /** Returns the code document that this component is editing. */
  38968. CodeDocument& getDocument() const noexcept { return document; }
  38969. /** Loads the given content into the document.
  38970. This will completely reset the CodeDocument object, clear its undo history,
  38971. and fill it with this text.
  38972. */
  38973. void loadContent (const String& newContent);
  38974. /** Returns the standard character width. */
  38975. float getCharWidth() const noexcept { return charWidth; }
  38976. /** Returns the height of a line of text, in pixels. */
  38977. int getLineHeight() const noexcept { return lineHeight; }
  38978. /** Returns the number of whole lines visible on the screen,
  38979. This doesn't include a cut-off line that might be visible at the bottom if the
  38980. component's height isn't an exact multiple of the line-height.
  38981. */
  38982. int getNumLinesOnScreen() const noexcept { return linesOnScreen; }
  38983. /** Returns the number of whole columns visible on the screen.
  38984. This doesn't include any cut-off columns at the right-hand edge.
  38985. */
  38986. int getNumColumnsOnScreen() const noexcept { return columnsOnScreen; }
  38987. /** Returns the current caret position. */
  38988. const CodeDocument::Position getCaretPos() const { return caretPos; }
  38989. /** Returns the position of the caret, relative to the editor's origin. */
  38990. const Rectangle<int> getCaretRectangle();
  38991. /** Moves the caret.
  38992. If selecting is true, the section of the document between the current
  38993. caret position and the new one will become selected. If false, any currently
  38994. selected region will be deselected.
  38995. */
  38996. void moveCaretTo (const CodeDocument::Position& newPos, bool selecting);
  38997. /** Returns the on-screen position of a character in the document.
  38998. The rectangle returned is relative to this component's top-left origin.
  38999. */
  39000. const Rectangle<int> getCharacterBounds (const CodeDocument::Position& pos) const;
  39001. /** Finds the character at a given on-screen position.
  39002. The co-ordinates are relative to this component's top-left origin.
  39003. */
  39004. const CodeDocument::Position getPositionAt (int x, int y);
  39005. bool moveCaretLeft (bool moveInWholeWordSteps, bool selecting);
  39006. bool moveCaretRight (bool moveInWholeWordSteps, bool selecting);
  39007. bool moveCaretUp (bool selecting);
  39008. bool moveCaretDown (bool selecting);
  39009. bool scrollDown();
  39010. bool scrollUp();
  39011. bool pageUp (bool selecting);
  39012. bool pageDown (bool selecting);
  39013. bool moveCaretToTop (bool selecting);
  39014. bool moveCaretToStartOfLine (bool selecting);
  39015. bool moveCaretToEnd (bool selecting);
  39016. bool moveCaretToEndOfLine (bool selecting);
  39017. bool deleteBackwards (bool moveInWholeWordSteps);
  39018. bool deleteForwards (bool moveInWholeWordSteps);
  39019. bool copyToClipboard();
  39020. bool cutToClipboard();
  39021. bool pasteFromClipboard();
  39022. bool undo();
  39023. bool redo();
  39024. bool selectAll();
  39025. void deselectAll();
  39026. void scrollToLine (int newFirstLineOnScreen);
  39027. void scrollBy (int deltaLines);
  39028. void scrollToColumn (int newFirstColumnOnScreen);
  39029. void scrollToKeepCaretOnScreen();
  39030. void insertTextAtCaret (const String& textToInsert);
  39031. void insertTabAtCaret();
  39032. const Range<int> getHighlightedRegion() const;
  39033. void setHighlightedRegion (const Range<int>& newRange);
  39034. const String getTextInRange (const Range<int>& range) const;
  39035. /** Changes the current tab settings.
  39036. This lets you change the tab size and whether pressing the tab key inserts a
  39037. tab character, or its equivalent number of spaces.
  39038. */
  39039. void setTabSize (int numSpacesPerTab, bool insertSpacesInsteadOfTabCharacters);
  39040. /** Returns the current number of spaces per tab.
  39041. @see setTabSize
  39042. */
  39043. int getTabSize() const noexcept { return spacesPerTab; }
  39044. /** Returns true if the tab key will insert spaces instead of actual tab characters.
  39045. @see setTabSize
  39046. */
  39047. bool areSpacesInsertedForTabs() const { return useSpacesForTabs; }
  39048. /** Changes the font.
  39049. Make sure you only use a fixed-width font, or this component will look pretty nasty!
  39050. */
  39051. void setFont (const Font& newFont);
  39052. /** Returns the font that the editor is using. */
  39053. const Font& getFont() const noexcept { return font; }
  39054. /** Resets the syntax highlighting colours to the default ones provided by the
  39055. code tokeniser.
  39056. @see CodeTokeniser::getDefaultColour
  39057. */
  39058. void resetToDefaultColours();
  39059. /** Changes one of the syntax highlighting colours.
  39060. The token type values are dependent on the tokeniser being used - use
  39061. CodeTokeniser::getTokenTypes() to get a list of the token types.
  39062. @see getColourForTokenType
  39063. */
  39064. void setColourForTokenType (int tokenType, const Colour& colour);
  39065. /** Returns one of the syntax highlighting colours.
  39066. The token type values are dependent on the tokeniser being used - use
  39067. CodeTokeniser::getTokenTypes() to get a list of the token types.
  39068. @see setColourForTokenType
  39069. */
  39070. const Colour getColourForTokenType (int tokenType) const;
  39071. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  39072. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39073. methods.
  39074. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39075. */
  39076. enum ColourIds
  39077. {
  39078. backgroundColourId = 0x1004500, /**< A colour to use to fill the editor's background. */
  39079. highlightColourId = 0x1004502, /**< The colour to use for the highlighted background under
  39080. selected text. */
  39081. defaultTextColourId = 0x1004503 /**< The colour to use for text when no syntax colouring is
  39082. enabled. */
  39083. };
  39084. /** Changes the size of the scrollbars. */
  39085. void setScrollbarThickness (int thickness);
  39086. /** Returns the thickness of the scrollbars. */
  39087. int getScrollbarThickness() const noexcept { return scrollbarThickness; }
  39088. /** @internal */
  39089. void resized();
  39090. /** @internal */
  39091. void paint (Graphics& g);
  39092. /** @internal */
  39093. bool keyPressed (const KeyPress& key);
  39094. /** @internal */
  39095. void mouseDown (const MouseEvent& e);
  39096. /** @internal */
  39097. void mouseDrag (const MouseEvent& e);
  39098. /** @internal */
  39099. void mouseUp (const MouseEvent& e);
  39100. /** @internal */
  39101. void mouseDoubleClick (const MouseEvent& e);
  39102. /** @internal */
  39103. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  39104. /** @internal */
  39105. void focusGained (FocusChangeType cause);
  39106. /** @internal */
  39107. void focusLost (FocusChangeType cause);
  39108. /** @internal */
  39109. void timerCallback();
  39110. /** @internal */
  39111. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  39112. /** @internal */
  39113. void handleAsyncUpdate();
  39114. /** @internal */
  39115. void codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  39116. const CodeDocument::Position& affectedTextEnd);
  39117. /** @internal */
  39118. bool isTextInputActive() const;
  39119. /** @internal */
  39120. void setTemporaryUnderlining (const Array <Range<int> >&);
  39121. private:
  39122. CodeDocument& document;
  39123. Font font;
  39124. int firstLineOnScreen, gutter, spacesPerTab;
  39125. float charWidth;
  39126. int lineHeight, linesOnScreen, columnsOnScreen;
  39127. int scrollbarThickness, columnToTryToMaintain;
  39128. bool useSpacesForTabs;
  39129. double xOffset;
  39130. CodeDocument::Position caretPos;
  39131. CodeDocument::Position selectionStart, selectionEnd;
  39132. ScopedPointer<CaretComponent> caret;
  39133. ScrollBar verticalScrollBar, horizontalScrollBar;
  39134. enum DragType
  39135. {
  39136. notDragging,
  39137. draggingSelectionStart,
  39138. draggingSelectionEnd
  39139. };
  39140. DragType dragType;
  39141. CodeTokeniser* codeTokeniser;
  39142. Array <Colour> coloursForTokenCategories;
  39143. class CodeEditorLine;
  39144. OwnedArray <CodeEditorLine> lines;
  39145. void rebuildLineTokens();
  39146. OwnedArray <CodeDocument::Iterator> cachedIterators;
  39147. void clearCachedIterators (int firstLineToBeInvalid);
  39148. void updateCachedIterators (int maxLineNum);
  39149. void getIteratorForPosition (int position, CodeDocument::Iterator& result);
  39150. void moveLineDelta (int delta, bool selecting);
  39151. void updateCaretPosition();
  39152. void updateScrollBars();
  39153. void scrollToLineInternal (int line);
  39154. void scrollToColumnInternal (double column);
  39155. void newTransaction();
  39156. void cut();
  39157. int indexToColumn (int line, int index) const noexcept;
  39158. int columnToIndex (int line, int column) const noexcept;
  39159. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CodeEditorComponent);
  39160. };
  39161. #endif // __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  39162. /*** End of inlined file: juce_CodeEditorComponent.h ***/
  39163. #endif
  39164. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  39165. #endif
  39166. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  39167. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  39168. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  39169. #define __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  39170. /**
  39171. A simple lexical analyser for syntax colouring of C++ code.
  39172. @see SyntaxAnalyser, CodeEditorComponent, CodeDocument
  39173. */
  39174. class JUCE_API CPlusPlusCodeTokeniser : public CodeTokeniser
  39175. {
  39176. public:
  39177. CPlusPlusCodeTokeniser();
  39178. ~CPlusPlusCodeTokeniser();
  39179. enum TokenType
  39180. {
  39181. tokenType_error = 0,
  39182. tokenType_comment,
  39183. tokenType_builtInKeyword,
  39184. tokenType_identifier,
  39185. tokenType_integerLiteral,
  39186. tokenType_floatLiteral,
  39187. tokenType_stringLiteral,
  39188. tokenType_operator,
  39189. tokenType_bracket,
  39190. tokenType_punctuation,
  39191. tokenType_preprocessor
  39192. };
  39193. int readNextToken (CodeDocument::Iterator& source);
  39194. StringArray getTokenTypes();
  39195. const Colour getDefaultColour (int tokenType);
  39196. /** This is a handy method for checking whether a string is a c++ reserved keyword. */
  39197. static bool isReservedKeyword (const String& token) noexcept;
  39198. private:
  39199. JUCE_LEAK_DETECTOR (CPlusPlusCodeTokeniser);
  39200. };
  39201. #endif // __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  39202. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  39203. #endif
  39204. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  39205. /*** Start of inlined file: juce_ComboBox.h ***/
  39206. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  39207. #define __JUCE_COMBOBOX_JUCEHEADER__
  39208. /*** Start of inlined file: juce_Label.h ***/
  39209. #ifndef __JUCE_LABEL_JUCEHEADER__
  39210. #define __JUCE_LABEL_JUCEHEADER__
  39211. /*** Start of inlined file: juce_TextEditor.h ***/
  39212. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  39213. #define __JUCE_TEXTEDITOR_JUCEHEADER__
  39214. /**
  39215. A component containing text that can be edited.
  39216. A TextEditor can either be in single- or multi-line mode, and supports mixed
  39217. fonts and colours.
  39218. @see TextEditor::Listener, Label
  39219. */
  39220. class JUCE_API TextEditor : public Component,
  39221. public TextInputTarget,
  39222. public SettableTooltipClient
  39223. {
  39224. public:
  39225. /** Creates a new, empty text editor.
  39226. @param componentName the name to pass to the component for it to use as its name
  39227. @param passwordCharacter if this is not zero, this character will be used as a replacement
  39228. for all characters that are drawn on screen - e.g. to create
  39229. a password-style textbox containing circular blobs instead of text,
  39230. you could set this value to 0x25cf, which is the unicode character
  39231. for a black splodge (not all fonts include this, though), or 0x2022,
  39232. which is a bullet (probably the best choice for linux).
  39233. */
  39234. explicit TextEditor (const String& componentName = String::empty,
  39235. juce_wchar passwordCharacter = 0);
  39236. /** Destructor. */
  39237. virtual ~TextEditor();
  39238. /** Puts the editor into either multi- or single-line mode.
  39239. By default, the editor will be in single-line mode, so use this if you need a multi-line
  39240. editor.
  39241. See also the setReturnKeyStartsNewLine() method, which will also need to be turned
  39242. on if you want a multi-line editor with line-breaks.
  39243. @see isMultiLine, setReturnKeyStartsNewLine
  39244. */
  39245. void setMultiLine (bool shouldBeMultiLine,
  39246. bool shouldWordWrap = true);
  39247. /** Returns true if the editor is in multi-line mode.
  39248. */
  39249. bool isMultiLine() const;
  39250. /** Changes the behaviour of the return key.
  39251. If set to true, the return key will insert a new-line into the text; if false
  39252. it will trigger a call to the TextEditor::Listener::textEditorReturnKeyPressed()
  39253. method. By default this is set to false, and when true it will only insert
  39254. new-lines when in multi-line mode (see setMultiLine()).
  39255. */
  39256. void setReturnKeyStartsNewLine (bool shouldStartNewLine);
  39257. /** Returns the value set by setReturnKeyStartsNewLine().
  39258. See setReturnKeyStartsNewLine() for more info.
  39259. */
  39260. bool getReturnKeyStartsNewLine() const { return returnKeyStartsNewLine; }
  39261. /** Indicates whether the tab key should be accepted and used to input a tab character,
  39262. or whether it gets ignored.
  39263. By default the tab key is ignored, so that it can be used to switch keyboard focus
  39264. between components.
  39265. */
  39266. void setTabKeyUsedAsCharacter (bool shouldTabKeyBeUsed);
  39267. /** Returns true if the tab key is being used for input.
  39268. @see setTabKeyUsedAsCharacter
  39269. */
  39270. bool isTabKeyUsedAsCharacter() const { return tabKeyUsed; }
  39271. /** Changes the editor to read-only mode.
  39272. By default, the text editor is not read-only. If you're making it read-only, you
  39273. might also want to call setCaretVisible (false) to get rid of the caret.
  39274. The text can still be highlighted and copied when in read-only mode.
  39275. @see isReadOnly, setCaretVisible
  39276. */
  39277. void setReadOnly (bool shouldBeReadOnly);
  39278. /** Returns true if the editor is in read-only mode.
  39279. */
  39280. bool isReadOnly() const;
  39281. /** Makes the caret visible or invisible.
  39282. By default the caret is visible.
  39283. @see setCaretColour, setCaretPosition
  39284. */
  39285. void setCaretVisible (bool shouldBeVisible);
  39286. /** Returns true if the caret is enabled.
  39287. @see setCaretVisible
  39288. */
  39289. bool isCaretVisible() const { return caret != nullptr; }
  39290. /** Enables/disables a vertical scrollbar.
  39291. (This only applies when in multi-line mode). When the text gets too long to fit
  39292. in the component, a scrollbar can appear to allow it to be scrolled. Even when
  39293. this is enabled, the scrollbar will be hidden unless it's needed.
  39294. By default the scrollbar is enabled.
  39295. */
  39296. void setScrollbarsShown (bool shouldBeEnabled);
  39297. /** Returns true if scrollbars are enabled.
  39298. @see setScrollbarsShown
  39299. */
  39300. bool areScrollbarsShown() const { return scrollbarVisible; }
  39301. /** Changes the password character used to disguise the text.
  39302. @param passwordCharacter if this is not zero, this character will be used as a replacement
  39303. for all characters that are drawn on screen - e.g. to create
  39304. a password-style textbox containing circular blobs instead of text,
  39305. you could set this value to 0x25cf, which is the unicode character
  39306. for a black splodge (not all fonts include this, though), or 0x2022,
  39307. which is a bullet (probably the best choice for linux).
  39308. */
  39309. void setPasswordCharacter (juce_wchar passwordCharacter);
  39310. /** Returns the current password character.
  39311. @see setPasswordCharacter
  39312. */
  39313. juce_wchar getPasswordCharacter() const { return passwordCharacter; }
  39314. /** Allows a right-click menu to appear for the editor.
  39315. (This defaults to being enabled).
  39316. If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
  39317. of options such as cut/copy/paste, undo/redo, etc.
  39318. */
  39319. void setPopupMenuEnabled (bool menuEnabled);
  39320. /** Returns true if the right-click menu is enabled.
  39321. @see setPopupMenuEnabled
  39322. */
  39323. bool isPopupMenuEnabled() const { return popupMenuEnabled; }
  39324. /** Returns true if a popup-menu is currently being displayed.
  39325. */
  39326. bool isPopupMenuCurrentlyActive() const { return menuActive; }
  39327. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  39328. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39329. methods.
  39330. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39331. */
  39332. enum ColourIds
  39333. {
  39334. backgroundColourId = 0x1000200, /**< The colour to use for the text component's background - this can be
  39335. transparent if necessary. */
  39336. textColourId = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
  39337. that because the editor can contain multiple colours, calling this
  39338. method won't change the colour of existing text - to do that, call
  39339. applyFontToAllText() after calling this method.*/
  39340. highlightColourId = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
  39341. the text - this can be transparent if you don't want to show any
  39342. highlighting.*/
  39343. highlightedTextColourId = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */
  39344. outlineColourId = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
  39345. the edge of the component. */
  39346. focusedOutlineColourId = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
  39347. the edge of the component when it has focus. */
  39348. shadowColourId = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
  39349. around the edge of the editor. */
  39350. };
  39351. /** Sets the font to use for newly added text.
  39352. This will change the font that will be used next time any text is added or entered
  39353. into the editor. It won't change the font of any existing text - to do that, use
  39354. applyFontToAllText() instead.
  39355. @see applyFontToAllText
  39356. */
  39357. void setFont (const Font& newFont);
  39358. /** Applies a font to all the text in the editor.
  39359. This will also set the current font to use for any new text that's added.
  39360. @see setFont
  39361. */
  39362. void applyFontToAllText (const Font& newFont);
  39363. /** Returns the font that's currently being used for new text.
  39364. @see setFont
  39365. */
  39366. const Font& getFont() const;
  39367. /** If set to true, focusing on the editor will highlight all its text.
  39368. (Set to false by default).
  39369. This is useful for boxes where you expect the user to re-enter all the
  39370. text when they focus on the component, rather than editing what's already there.
  39371. */
  39372. void setSelectAllWhenFocused (bool b);
  39373. /** Sets limits on the characters that can be entered.
  39374. @param maxTextLength if this is > 0, it sets a maximum length limit; if 0, no
  39375. limit is set
  39376. @param allowedCharacters if this is non-empty, then only characters that occur in
  39377. this string are allowed to be entered into the editor.
  39378. */
  39379. void setInputRestrictions (int maxTextLength,
  39380. const String& allowedCharacters = String::empty);
  39381. /** When the text editor is empty, it can be set to display a message.
  39382. This is handy for things like telling the user what to type in the box - the
  39383. string is only displayed, it's not taken to actually be the contents of
  39384. the editor.
  39385. */
  39386. void setTextToShowWhenEmpty (const String& text, const Colour& colourToUse);
  39387. /** Changes the size of the scrollbars that are used.
  39388. Handy if you need smaller scrollbars for a small text box.
  39389. */
  39390. void setScrollBarThickness (int newThicknessPixels);
  39391. /** Shows or hides the buttons on any scrollbars that are used.
  39392. @see ScrollBar::setButtonVisibility
  39393. */
  39394. void setScrollBarButtonVisibility (bool buttonsVisible);
  39395. /**
  39396. Receives callbacks from a TextEditor component when it changes.
  39397. @see TextEditor::addListener
  39398. */
  39399. class JUCE_API Listener
  39400. {
  39401. public:
  39402. /** Destructor. */
  39403. virtual ~Listener() {}
  39404. /** Called when the user changes the text in some way. */
  39405. virtual void textEditorTextChanged (TextEditor& editor);
  39406. /** Called when the user presses the return key. */
  39407. virtual void textEditorReturnKeyPressed (TextEditor& editor);
  39408. /** Called when the user presses the escape key. */
  39409. virtual void textEditorEscapeKeyPressed (TextEditor& editor);
  39410. /** Called when the text editor loses focus. */
  39411. virtual void textEditorFocusLost (TextEditor& editor);
  39412. };
  39413. /** Registers a listener to be told when things happen to the text.
  39414. @see removeListener
  39415. */
  39416. void addListener (Listener* newListener);
  39417. /** Deregisters a listener.
  39418. @see addListener
  39419. */
  39420. void removeListener (Listener* listenerToRemove);
  39421. /** Returns the entire contents of the editor. */
  39422. String getText() const;
  39423. /** Returns a section of the contents of the editor. */
  39424. const String getTextInRange (const Range<int>& textRange) const;
  39425. /** Returns true if there are no characters in the editor.
  39426. This is more efficient than calling getText().isEmpty().
  39427. */
  39428. bool isEmpty() const;
  39429. /** Sets the entire content of the editor.
  39430. This will clear the editor and insert the given text (using the current text colour
  39431. and font). You can set the current text colour using
  39432. @code setColour (TextEditor::textColourId, ...);
  39433. @endcode
  39434. @param newText the text to add
  39435. @param sendTextChangeMessage if true, this will cause a change message to
  39436. be sent to all the listeners.
  39437. @see insertText
  39438. */
  39439. void setText (const String& newText,
  39440. bool sendTextChangeMessage = true);
  39441. /** Returns a Value object that can be used to get or set the text.
  39442. Bear in mind that this operate quite slowly if your text box contains large
  39443. amounts of text, as it needs to dynamically build the string that's involved. It's
  39444. best used for small text boxes.
  39445. */
  39446. Value& getTextValue();
  39447. /** Inserts some text at the current caret position.
  39448. If a section of the text is highlighted, it will be replaced by
  39449. this string, otherwise it will be inserted.
  39450. To delete a section of text, you can use setHighlightedRegion() to
  39451. highlight it, and call insertTextAtCursor (String::empty).
  39452. @see setCaretPosition, getCaretPosition, setHighlightedRegion
  39453. */
  39454. void insertTextAtCaret (const String& textToInsert);
  39455. /** Deletes all the text from the editor. */
  39456. void clear();
  39457. /** Deletes the currently selected region.
  39458. This doesn't copy the deleted section to the clipboard - if you need to do that, call copy() first.
  39459. @see copy, paste, SystemClipboard
  39460. */
  39461. void cut();
  39462. /** Copies the currently selected region to the clipboard.
  39463. @see cut, paste, SystemClipboard
  39464. */
  39465. void copy();
  39466. /** Pastes the contents of the clipboard into the editor at the caret position.
  39467. @see cut, copy, SystemClipboard
  39468. */
  39469. void paste();
  39470. /** Moves the caret to be in front of a given character.
  39471. @see getCaretPosition
  39472. */
  39473. void setCaretPosition (int newIndex);
  39474. /** Returns the current index of the caret.
  39475. @see setCaretPosition
  39476. */
  39477. int getCaretPosition() const;
  39478. /** Attempts to scroll the text editor so that the caret ends up at
  39479. a specified position.
  39480. This won't affect the caret's position within the text, it tries to scroll
  39481. the entire editor vertically and horizontally so that the caret is sitting
  39482. at the given position (relative to the top-left of this component).
  39483. Depending on the amount of text available, it might not be possible to
  39484. scroll far enough for the caret to reach this exact position, but it
  39485. will go as far as it can in that direction.
  39486. */
  39487. void scrollEditorToPositionCaret (int desiredCaretX, int desiredCaretY);
  39488. /** Get the graphical position of the caret.
  39489. The rectangle returned is relative to the component's top-left corner.
  39490. @see scrollEditorToPositionCaret
  39491. */
  39492. const Rectangle<int> getCaretRectangle();
  39493. /** Selects a section of the text. */
  39494. void setHighlightedRegion (const Range<int>& newSelection);
  39495. /** Returns the range of characters that are selected.
  39496. If nothing is selected, this will return an empty range.
  39497. @see setHighlightedRegion
  39498. */
  39499. const Range<int> getHighlightedRegion() const { return selection; }
  39500. /** Returns the section of text that is currently selected. */
  39501. String getHighlightedText() const;
  39502. /** Finds the index of the character at a given position.
  39503. The co-ordinates are relative to the component's top-left.
  39504. */
  39505. int getTextIndexAt (int x, int y);
  39506. /** Counts the number of characters in the text.
  39507. This is quicker than getting the text as a string if you just need to know
  39508. the length.
  39509. */
  39510. int getTotalNumChars() const;
  39511. /** Returns the total width of the text, as it is currently laid-out.
  39512. This may be larger than the size of the TextEditor, and can change when
  39513. the TextEditor is resized or the text changes.
  39514. */
  39515. int getTextWidth() const;
  39516. /** Returns the maximum height of the text, as it is currently laid-out.
  39517. This may be larger than the size of the TextEditor, and can change when
  39518. the TextEditor is resized or the text changes.
  39519. */
  39520. int getTextHeight() const;
  39521. /** Changes the size of the gap at the top and left-edge of the editor.
  39522. By default there's a gap of 4 pixels.
  39523. */
  39524. void setIndents (int newLeftIndent, int newTopIndent);
  39525. /** Changes the size of border left around the edge of the component.
  39526. @see getBorder
  39527. */
  39528. void setBorder (const BorderSize<int>& border);
  39529. /** Returns the size of border around the edge of the component.
  39530. @see setBorder
  39531. */
  39532. const BorderSize<int> getBorder() const;
  39533. /** Used to disable the auto-scrolling which keeps the caret visible.
  39534. If true (the default), the editor will scroll when the caret moves offscreen. If
  39535. set to false, it won't.
  39536. */
  39537. void setScrollToShowCursor (bool shouldScrollToShowCaret);
  39538. /** @internal */
  39539. void paint (Graphics& g);
  39540. /** @internal */
  39541. void paintOverChildren (Graphics& g);
  39542. /** @internal */
  39543. void mouseDown (const MouseEvent& e);
  39544. /** @internal */
  39545. void mouseUp (const MouseEvent& e);
  39546. /** @internal */
  39547. void mouseDrag (const MouseEvent& e);
  39548. /** @internal */
  39549. void mouseDoubleClick (const MouseEvent& e);
  39550. /** @internal */
  39551. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  39552. /** @internal */
  39553. bool keyPressed (const KeyPress& key);
  39554. /** @internal */
  39555. bool keyStateChanged (bool isKeyDown);
  39556. /** @internal */
  39557. void focusGained (FocusChangeType cause);
  39558. /** @internal */
  39559. void focusLost (FocusChangeType cause);
  39560. /** @internal */
  39561. void resized();
  39562. /** @internal */
  39563. void enablementChanged();
  39564. /** @internal */
  39565. void colourChanged();
  39566. /** @internal */
  39567. void lookAndFeelChanged();
  39568. /** @internal */
  39569. bool isTextInputActive() const;
  39570. /** @internal */
  39571. void setTemporaryUnderlining (const Array <Range<int> >&);
  39572. bool moveCaretLeft (bool moveInWholeWordSteps, bool selecting);
  39573. bool moveCaretRight (bool moveInWholeWordSteps, bool selecting);
  39574. bool moveCaretUp (bool selecting);
  39575. bool moveCaretDown (bool selecting);
  39576. bool pageUp (bool selecting);
  39577. bool pageDown (bool selecting);
  39578. bool scrollDown();
  39579. bool scrollUp();
  39580. bool moveCaretToTop (bool selecting);
  39581. bool moveCaretToStartOfLine (bool selecting);
  39582. bool moveCaretToEnd (bool selecting);
  39583. bool moveCaretToEndOfLine (bool selecting);
  39584. bool deleteBackwards (bool moveInWholeWordSteps);
  39585. bool deleteForwards (bool moveInWholeWordSteps);
  39586. bool copyToClipboard();
  39587. bool cutToClipboard();
  39588. bool pasteFromClipboard();
  39589. bool selectAll();
  39590. bool undo();
  39591. bool redo();
  39592. /** This adds the items to the popup menu.
  39593. By default it adds the cut/copy/paste items, but you can override this if
  39594. you need to replace these with your own items.
  39595. If you want to add your own items to the existing ones, you can override this,
  39596. call the base class's addPopupMenuItems() method, then append your own items.
  39597. When the menu has been shown, performPopupMenuAction() will be called to
  39598. perform the item that the user has chosen.
  39599. The default menu items will be added using item IDs in the range
  39600. 0x7fff0000 - 0x7fff1000, so you should avoid those values for your own
  39601. menu IDs.
  39602. If this was triggered by a mouse-click, the mouseClickEvent parameter will be
  39603. a pointer to the info about it, or may be null if the menu is being triggered
  39604. by some other means.
  39605. @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
  39606. */
  39607. virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
  39608. const MouseEvent* mouseClickEvent);
  39609. /** This is called to perform one of the items that was shown on the popup menu.
  39610. If you've overridden addPopupMenuItems(), you should also override this
  39611. to perform the actions that you've added.
  39612. If you've overridden addPopupMenuItems() but have still left the default items
  39613. on the menu, remember to call the superclass's performPopupMenuAction()
  39614. so that it can perform the default actions if that's what the user clicked on.
  39615. @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
  39616. */
  39617. virtual void performPopupMenuAction (int menuItemID);
  39618. protected:
  39619. /** Scrolls the minimum distance needed to get the caret into view. */
  39620. void scrollToMakeSureCursorIsVisible();
  39621. /** @internal */
  39622. void moveCaret (int newCaretPos);
  39623. /** @internal */
  39624. void moveCaretTo (int newPosition, bool isSelecting);
  39625. /** Used internally to dispatch a text-change message. */
  39626. void textChanged();
  39627. /** Begins a new transaction in the UndoManager. */
  39628. void newTransaction();
  39629. /** Used internally to trigger an undo or redo. */
  39630. void doUndoRedo (bool isRedo);
  39631. /** Can be overridden to intercept return key presses directly */
  39632. virtual void returnPressed();
  39633. /** Can be overridden to intercept escape key presses directly */
  39634. virtual void escapePressed();
  39635. /** @internal */
  39636. void handleCommandMessage (int commandId);
  39637. private:
  39638. class Iterator;
  39639. class UniformTextSection;
  39640. class TextHolderComponent;
  39641. class InsertAction;
  39642. class RemoveAction;
  39643. friend class InsertAction;
  39644. friend class RemoveAction;
  39645. ScopedPointer <Viewport> viewport;
  39646. TextHolderComponent* textHolder;
  39647. BorderSize<int> borderSize;
  39648. bool readOnly : 1;
  39649. bool multiline : 1;
  39650. bool wordWrap : 1;
  39651. bool returnKeyStartsNewLine : 1;
  39652. bool popupMenuEnabled : 1;
  39653. bool selectAllTextWhenFocused : 1;
  39654. bool scrollbarVisible : 1;
  39655. bool wasFocused : 1;
  39656. bool keepCaretOnScreen : 1;
  39657. bool tabKeyUsed : 1;
  39658. bool menuActive : 1;
  39659. bool valueTextNeedsUpdating : 1;
  39660. UndoManager undoManager;
  39661. ScopedPointer<CaretComponent> caret;
  39662. int maxTextLength;
  39663. Range<int> selection;
  39664. int leftIndent, topIndent;
  39665. unsigned int lastTransactionTime;
  39666. Font currentFont;
  39667. mutable int totalNumChars;
  39668. int caretPosition;
  39669. Array <UniformTextSection*> sections;
  39670. String textToShowWhenEmpty;
  39671. Colour colourForTextWhenEmpty;
  39672. juce_wchar passwordCharacter;
  39673. Value textValue;
  39674. enum
  39675. {
  39676. notDragging,
  39677. draggingSelectionStart,
  39678. draggingSelectionEnd
  39679. } dragType;
  39680. String allowedCharacters;
  39681. ListenerList <Listener> listeners;
  39682. Array <Range<int> > underlinedSections;
  39683. void coalesceSimilarSections();
  39684. void splitSection (int sectionIndex, int charToSplitAt);
  39685. void clearInternal (UndoManager* um);
  39686. void insert (const String& text, int insertIndex, const Font& font,
  39687. const Colour& colour, UndoManager* um, int caretPositionToMoveTo);
  39688. void reinsert (int insertIndex, const Array <UniformTextSection*>& sections);
  39689. void remove (const Range<int>& range, UndoManager* um, int caretPositionToMoveTo);
  39690. void getCharPosition (int index, float& x, float& y, float& lineHeight) const;
  39691. void updateCaretPosition();
  39692. void updateValueFromText();
  39693. void textWasChangedByValue();
  39694. int indexAtPosition (float x, float y);
  39695. int findWordBreakAfter (int position) const;
  39696. int findWordBreakBefore (int position) const;
  39697. bool moveCaretWithTransation (int newPos, bool selecting);
  39698. friend class TextHolderComponent;
  39699. friend class TextEditorViewport;
  39700. void drawContent (Graphics& g);
  39701. void updateTextHolderSize();
  39702. float getWordWrapWidth() const;
  39703. void timerCallbackInt();
  39704. void repaintText (const Range<int>& range);
  39705. void scrollByLines (int deltaLines);
  39706. bool undoOrRedo (bool shouldUndo);
  39707. UndoManager* getUndoManager() noexcept;
  39708. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextEditor);
  39709. };
  39710. /** This typedef is just for compatibility with old code - newer code should use the TextEditor::Listener class directly. */
  39711. typedef TextEditor::Listener TextEditorListener;
  39712. #endif // __JUCE_TEXTEDITOR_JUCEHEADER__
  39713. /*** End of inlined file: juce_TextEditor.h ***/
  39714. #if JUCE_VC6
  39715. #define Listener ButtonListener
  39716. #endif
  39717. /**
  39718. A component that displays a text string, and can optionally become a text
  39719. editor when clicked.
  39720. */
  39721. class JUCE_API Label : public Component,
  39722. public SettableTooltipClient,
  39723. protected TextEditorListener,
  39724. private ComponentListener,
  39725. private ValueListener
  39726. {
  39727. public:
  39728. /** Creates a Label.
  39729. @param componentName the name to give the component
  39730. @param labelText the text to show in the label
  39731. */
  39732. Label (const String& componentName = String::empty,
  39733. const String& labelText = String::empty);
  39734. /** Destructor. */
  39735. ~Label();
  39736. /** Changes the label text.
  39737. If broadcastChangeMessage is true and the new text is different to the current
  39738. text, then the class will broadcast a change message to any Label::Listener objects
  39739. that are registered.
  39740. */
  39741. void setText (const String& newText, bool broadcastChangeMessage);
  39742. /** Returns the label's current text.
  39743. @param returnActiveEditorContents if this is true and the label is currently
  39744. being edited, then this method will return the
  39745. text as it's being shown in the editor. If false,
  39746. then the value returned here won't be updated until
  39747. the user has finished typing and pressed the return
  39748. key.
  39749. */
  39750. String getText (bool returnActiveEditorContents = false) const;
  39751. /** Returns the text content as a Value object.
  39752. You can call Value::referTo() on this object to make the label read and control
  39753. a Value object that you supply.
  39754. */
  39755. Value& getTextValue() { return textValue; }
  39756. /** Changes the font to use to draw the text.
  39757. @see getFont
  39758. */
  39759. void setFont (const Font& newFont);
  39760. /** Returns the font currently being used.
  39761. @see setFont
  39762. */
  39763. const Font& getFont() const noexcept;
  39764. /** A set of colour IDs to use to change the colour of various aspects of the label.
  39765. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39766. methods.
  39767. Note that you can also use the constants from TextEditor::ColourIds to change the
  39768. colour of the text editor that is opened when a label is editable.
  39769. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39770. */
  39771. enum ColourIds
  39772. {
  39773. backgroundColourId = 0x1000280, /**< The background colour to fill the label with. */
  39774. textColourId = 0x1000281, /**< The colour for the text. */
  39775. outlineColourId = 0x1000282 /**< An optional colour to use to draw a border around the label.
  39776. Leave this transparent to not have an outline. */
  39777. };
  39778. /** Sets the style of justification to be used for positioning the text.
  39779. (The default is Justification::centredLeft)
  39780. */
  39781. void setJustificationType (const Justification& justification);
  39782. /** Returns the type of justification, as set in setJustificationType(). */
  39783. const Justification getJustificationType() const noexcept { return justification; }
  39784. /** Changes the gap that is left between the edge of the component and the text.
  39785. By default there's a small gap left at the sides of the component to allow for
  39786. the drawing of the border, but you can change this if necessary.
  39787. */
  39788. void setBorderSize (int horizontalBorder, int verticalBorder);
  39789. /** Returns the size of the horizontal gap being left around the text.
  39790. */
  39791. int getHorizontalBorderSize() const noexcept { return horizontalBorderSize; }
  39792. /** Returns the size of the vertical gap being left around the text.
  39793. */
  39794. int getVerticalBorderSize() const noexcept { return verticalBorderSize; }
  39795. /** Makes this label "stick to" another component.
  39796. This will cause the label to follow another component around, staying
  39797. either to its left or above it.
  39798. @param owner the component to follow
  39799. @param onLeft if true, the label will stay on the left of its component; if
  39800. false, it will stay above it.
  39801. */
  39802. void attachToComponent (Component* owner, bool onLeft);
  39803. /** If this label has been attached to another component using attachToComponent, this
  39804. returns the other component.
  39805. Returns 0 if the label is not attached.
  39806. */
  39807. Component* getAttachedComponent() const;
  39808. /** If the label is attached to the left of another component, this returns true.
  39809. Returns false if the label is above the other component. This is only relevent if
  39810. attachToComponent() has been called.
  39811. */
  39812. bool isAttachedOnLeft() const noexcept { return leftOfOwnerComp; }
  39813. /** Specifies the minimum amount that the font can be squashed horizantally before it starts
  39814. using ellipsis.
  39815. @see Graphics::drawFittedText
  39816. */
  39817. void setMinimumHorizontalScale (float newScale);
  39818. float getMinimumHorizontalScale() const noexcept { return minimumHorizontalScale; }
  39819. /**
  39820. A class for receiving events from a Label.
  39821. You can register a Label::Listener with a Label using the Label::addListener()
  39822. method, and it will be called when the text of the label changes, either because
  39823. of a call to Label::setText() or by the user editing the text (if the label is
  39824. editable).
  39825. @see Label::addListener, Label::removeListener
  39826. */
  39827. class JUCE_API Listener
  39828. {
  39829. public:
  39830. /** Destructor. */
  39831. virtual ~Listener() {}
  39832. /** Called when a Label's text has changed.
  39833. */
  39834. virtual void labelTextChanged (Label* labelThatHasChanged) = 0;
  39835. };
  39836. /** Registers a listener that will be called when the label's text changes. */
  39837. void addListener (Listener* listener);
  39838. /** Deregisters a previously-registered listener. */
  39839. void removeListener (Listener* listener);
  39840. /** Makes the label turn into a TextEditor when clicked.
  39841. By default this is turned off.
  39842. If turned on, then single- or double-clicking will turn the label into
  39843. an editor. If the user then changes the text, then the ChangeBroadcaster
  39844. base class will be used to send change messages to any listeners that
  39845. have registered.
  39846. If the user changes the text, the textWasEdited() method will be called
  39847. afterwards, and subclasses can override this if they need to do anything
  39848. special.
  39849. @param editOnSingleClick if true, just clicking once on the label will start editing the text
  39850. @param editOnDoubleClick if true, a double-click is needed to start editing
  39851. @param lossOfFocusDiscardsChanges if true, clicking somewhere else while the text is being
  39852. edited will discard any changes; if false, then this will
  39853. commit the changes.
  39854. @see showEditor, setEditorColours, TextEditor
  39855. */
  39856. void setEditable (bool editOnSingleClick,
  39857. bool editOnDoubleClick = false,
  39858. bool lossOfFocusDiscardsChanges = false);
  39859. /** Returns true if this option was set using setEditable(). */
  39860. bool isEditableOnSingleClick() const noexcept { return editSingleClick; }
  39861. /** Returns true if this option was set using setEditable(). */
  39862. bool isEditableOnDoubleClick() const noexcept { return editDoubleClick; }
  39863. /** Returns true if this option has been set in a call to setEditable(). */
  39864. bool doesLossOfFocusDiscardChanges() const noexcept { return lossOfFocusDiscardsChanges; }
  39865. /** Returns true if the user can edit this label's text. */
  39866. bool isEditable() const noexcept { return editSingleClick || editDoubleClick; }
  39867. /** Makes the editor appear as if the label had been clicked by the user.
  39868. @see textWasEdited, setEditable
  39869. */
  39870. void showEditor();
  39871. /** Hides the editor if it was being shown.
  39872. @param discardCurrentEditorContents if true, the label's text will be
  39873. reset to whatever it was before the editor
  39874. was shown; if false, the current contents of the
  39875. editor will be used to set the label's text
  39876. before it is hidden.
  39877. */
  39878. void hideEditor (bool discardCurrentEditorContents);
  39879. /** Returns true if the editor is currently focused and active. */
  39880. bool isBeingEdited() const noexcept;
  39881. protected:
  39882. /** Creates the TextEditor component that will be used when the user has clicked on the label.
  39883. Subclasses can override this if they need to customise this component in some way.
  39884. */
  39885. virtual TextEditor* createEditorComponent();
  39886. /** Called after the user changes the text. */
  39887. virtual void textWasEdited();
  39888. /** Called when the text has been altered. */
  39889. virtual void textWasChanged();
  39890. /** Called when the text editor has just appeared, due to a user click or other focus change. */
  39891. virtual void editorShown (TextEditor* editorComponent);
  39892. /** Called when the text editor is going to be deleted, after editing has finished. */
  39893. virtual void editorAboutToBeHidden (TextEditor* editorComponent);
  39894. /** @internal */
  39895. void paint (Graphics& g);
  39896. /** @internal */
  39897. void resized();
  39898. /** @internal */
  39899. void mouseUp (const MouseEvent& e);
  39900. /** @internal */
  39901. void mouseDoubleClick (const MouseEvent& e);
  39902. /** @internal */
  39903. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  39904. /** @internal */
  39905. void componentParentHierarchyChanged (Component& component);
  39906. /** @internal */
  39907. void componentVisibilityChanged (Component& component);
  39908. /** @internal */
  39909. void inputAttemptWhenModal();
  39910. /** @internal */
  39911. void focusGained (FocusChangeType);
  39912. /** @internal */
  39913. void enablementChanged();
  39914. /** @internal */
  39915. KeyboardFocusTraverser* createFocusTraverser();
  39916. /** @internal */
  39917. void textEditorTextChanged (TextEditor& editor);
  39918. /** @internal */
  39919. void textEditorReturnKeyPressed (TextEditor& editor);
  39920. /** @internal */
  39921. void textEditorEscapeKeyPressed (TextEditor& editor);
  39922. /** @internal */
  39923. void textEditorFocusLost (TextEditor& editor);
  39924. /** @internal */
  39925. void colourChanged();
  39926. /** @internal */
  39927. void valueChanged (Value&);
  39928. private:
  39929. Value textValue;
  39930. String lastTextValue;
  39931. Font font;
  39932. Justification justification;
  39933. ScopedPointer<TextEditor> editor;
  39934. ListenerList<Listener> listeners;
  39935. WeakReference<Component> ownerComponent;
  39936. int horizontalBorderSize, verticalBorderSize;
  39937. float minimumHorizontalScale;
  39938. bool editSingleClick : 1;
  39939. bool editDoubleClick : 1;
  39940. bool lossOfFocusDiscardsChanges : 1;
  39941. bool leftOfOwnerComp : 1;
  39942. bool updateFromTextEditorContents (TextEditor&);
  39943. void callChangeListeners();
  39944. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Label);
  39945. };
  39946. /** This typedef is just for compatibility with old code - newer code should use the Label::Listener class directly. */
  39947. typedef Label::Listener LabelListener;
  39948. #if JUCE_VC6
  39949. #undef Listener
  39950. #endif
  39951. #endif // __JUCE_LABEL_JUCEHEADER__
  39952. /*** End of inlined file: juce_Label.h ***/
  39953. #if JUCE_VC6
  39954. #define Listener SliderListener
  39955. #endif
  39956. /**
  39957. A component that lets the user choose from a drop-down list of choices.
  39958. The combo-box has a list of text strings, each with an associated id number,
  39959. that will be shown in the drop-down list when the user clicks on the component.
  39960. The currently selected choice is displayed in the combo-box, and this can
  39961. either be read-only text, or editable.
  39962. To find out when the user selects a different item or edits the text, you
  39963. can register a ComboBox::Listener to receive callbacks.
  39964. @see ComboBox::Listener
  39965. */
  39966. class JUCE_API ComboBox : public Component,
  39967. public SettableTooltipClient,
  39968. public LabelListener, // (can't use Label::Listener due to idiotic VC2005 bug)
  39969. public ValueListener,
  39970. private AsyncUpdater
  39971. {
  39972. public:
  39973. /** Creates a combo-box.
  39974. On construction, the text field will be empty, so you should call the
  39975. setSelectedId() or setText() method to choose the initial value before
  39976. displaying it.
  39977. @param componentName the name to set for the component (see Component::setName())
  39978. */
  39979. explicit ComboBox (const String& componentName = String::empty);
  39980. /** Destructor. */
  39981. ~ComboBox();
  39982. /** Sets whether the test in the combo-box is editable.
  39983. The default state for a new ComboBox is non-editable, and can only be changed
  39984. by choosing from the drop-down list.
  39985. */
  39986. void setEditableText (bool isEditable);
  39987. /** Returns true if the text is directly editable.
  39988. @see setEditableText
  39989. */
  39990. bool isTextEditable() const noexcept;
  39991. /** Sets the style of justification to be used for positioning the text.
  39992. The default is Justification::centredLeft. The text is displayed using a
  39993. Label component inside the ComboBox.
  39994. */
  39995. void setJustificationType (const Justification& justification);
  39996. /** Returns the current justification for the text box.
  39997. @see setJustificationType
  39998. */
  39999. const Justification getJustificationType() const noexcept;
  40000. /** Adds an item to be shown in the drop-down list.
  40001. @param newItemText the text of the item to show in the list
  40002. @param newItemId an associated ID number that can be set or retrieved - see
  40003. getSelectedId() and setSelectedId(). Note that this value can not
  40004. be 0!
  40005. @see setItemEnabled, addSeparator, addSectionHeading, removeItem, getNumItems, getItemText, getItemId
  40006. */
  40007. void addItem (const String& newItemText, int newItemId);
  40008. /** Adds a separator line to the drop-down list.
  40009. This is like adding a separator to a popup menu. See PopupMenu::addSeparator().
  40010. */
  40011. void addSeparator();
  40012. /** Adds a heading to the drop-down list, so that you can group the items into
  40013. different sections.
  40014. The headings are indented slightly differently to set them apart from the
  40015. items on the list, and obviously can't be selected. You might want to add
  40016. separators between your sections too.
  40017. @see addItem, addSeparator
  40018. */
  40019. void addSectionHeading (const String& headingName);
  40020. /** This allows items in the drop-down list to be selectively disabled.
  40021. When you add an item, it's enabled by default, but you can call this
  40022. method to change its status.
  40023. If you disable an item which is already selected, this won't change the
  40024. current selection - it just stops the user choosing that item from the list.
  40025. */
  40026. void setItemEnabled (int itemId, bool shouldBeEnabled);
  40027. /** Returns true if the given item is enabled. */
  40028. bool isItemEnabled (int itemId) const noexcept;
  40029. /** Changes the text for an existing item.
  40030. */
  40031. void changeItemText (int itemId, const String& newText);
  40032. /** Removes all the items from the drop-down list.
  40033. If this call causes the content to be cleared, then a change-message
  40034. will be broadcast unless dontSendChangeMessage is true.
  40035. @see addItem, removeItem, getNumItems
  40036. */
  40037. void clear (bool dontSendChangeMessage = false);
  40038. /** Returns the number of items that have been added to the list.
  40039. Note that this doesn't include headers or separators.
  40040. */
  40041. int getNumItems() const noexcept;
  40042. /** Returns the text for one of the items in the list.
  40043. Note that this doesn't include headers or separators.
  40044. @param index the item's index from 0 to (getNumItems() - 1)
  40045. */
  40046. String getItemText (int index) const;
  40047. /** Returns the ID for one of the items in the list.
  40048. Note that this doesn't include headers or separators.
  40049. @param index the item's index from 0 to (getNumItems() - 1)
  40050. */
  40051. int getItemId (int index) const noexcept;
  40052. /** Returns the index in the list of a particular item ID.
  40053. If no such ID is found, this will return -1.
  40054. */
  40055. int indexOfItemId (int itemId) const noexcept;
  40056. /** Returns the ID of the item that's currently shown in the box.
  40057. If no item is selected, or if the text is editable and the user
  40058. has entered something which isn't one of the items in the list, then
  40059. this will return 0.
  40060. @see setSelectedId, getSelectedItemIndex, getText
  40061. */
  40062. int getSelectedId() const noexcept;
  40063. /** Returns a Value object that can be used to get or set the selected item's ID.
  40064. You can call Value::referTo() on this object to make the combo box control
  40065. another Value object.
  40066. */
  40067. Value& getSelectedIdAsValue() { return currentId; }
  40068. /** Sets one of the items to be the current selection.
  40069. This will set the ComboBox's text to that of the item that matches
  40070. this ID.
  40071. @param newItemId the new item to select
  40072. @param dontSendChangeMessage if set to true, this method won't trigger a
  40073. change notification
  40074. @see getSelectedId, setSelectedItemIndex, setText
  40075. */
  40076. void setSelectedId (int newItemId, bool dontSendChangeMessage = false);
  40077. /** Returns the index of the item that's currently shown in the box.
  40078. If no item is selected, or if the text is editable and the user
  40079. has entered something which isn't one of the items in the list, then
  40080. this will return -1.
  40081. @see setSelectedItemIndex, getSelectedId, getText
  40082. */
  40083. int getSelectedItemIndex() const;
  40084. /** Sets one of the items to be the current selection.
  40085. This will set the ComboBox's text to that of the item at the given
  40086. index in the list.
  40087. @param newItemIndex the new item to select
  40088. @param dontSendChangeMessage if set to true, this method won't trigger a
  40089. change notification
  40090. @see getSelectedItemIndex, setSelectedId, setText
  40091. */
  40092. void setSelectedItemIndex (int newItemIndex, bool dontSendChangeMessage = false);
  40093. /** Returns the text that is currently shown in the combo-box's text field.
  40094. If the ComboBox has editable text, then this text may have been edited
  40095. by the user; otherwise it will be one of the items from the list, or
  40096. possibly an empty string if nothing was selected.
  40097. @see setText, getSelectedId, getSelectedItemIndex
  40098. */
  40099. String getText() const;
  40100. /** Sets the contents of the combo-box's text field.
  40101. The text passed-in will be set as the current text regardless of whether
  40102. it is one of the items in the list. If the current text isn't one of the
  40103. items, then getSelectedId() will return -1, otherwise it wil return
  40104. the approriate ID.
  40105. @param newText the text to select
  40106. @param dontSendChangeMessage if set to true, this method won't trigger a
  40107. change notification
  40108. @see getText
  40109. */
  40110. void setText (const String& newText, bool dontSendChangeMessage = false);
  40111. /** Programmatically opens the text editor to allow the user to edit the current item.
  40112. This is the same effect as when the box is clicked-on.
  40113. @see Label::showEditor();
  40114. */
  40115. void showEditor();
  40116. /** Pops up the combo box's list. */
  40117. void showPopup();
  40118. /**
  40119. A class for receiving events from a ComboBox.
  40120. You can register a ComboBox::Listener with a ComboBox using the ComboBox::addListener()
  40121. method, and it will be called when the selected item in the box changes.
  40122. @see ComboBox::addListener, ComboBox::removeListener
  40123. */
  40124. class JUCE_API Listener
  40125. {
  40126. public:
  40127. /** Destructor. */
  40128. virtual ~Listener() {}
  40129. /** Called when a ComboBox has its selected item changed. */
  40130. virtual void comboBoxChanged (ComboBox* comboBoxThatHasChanged) = 0;
  40131. };
  40132. /** Registers a listener that will be called when the box's content changes. */
  40133. void addListener (Listener* listener);
  40134. /** Deregisters a previously-registered listener. */
  40135. void removeListener (Listener* listener);
  40136. /** Sets a message to display when there is no item currently selected.
  40137. @see getTextWhenNothingSelected
  40138. */
  40139. void setTextWhenNothingSelected (const String& newMessage);
  40140. /** Returns the text that is shown when no item is selected.
  40141. @see setTextWhenNothingSelected
  40142. */
  40143. String getTextWhenNothingSelected() const;
  40144. /** Sets the message to show when there are no items in the list, and the user clicks
  40145. on the drop-down box.
  40146. By default it just says "no choices", but this lets you change it to something more
  40147. meaningful.
  40148. */
  40149. void setTextWhenNoChoicesAvailable (const String& newMessage);
  40150. /** Returns the text shown when no items have been added to the list.
  40151. @see setTextWhenNoChoicesAvailable
  40152. */
  40153. String getTextWhenNoChoicesAvailable() const;
  40154. /** Gives the ComboBox a tooltip. */
  40155. void setTooltip (const String& newTooltip);
  40156. /** A set of colour IDs to use to change the colour of various aspects of the combo box.
  40157. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  40158. methods.
  40159. To change the colours of the menu that pops up
  40160. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  40161. */
  40162. enum ColourIds
  40163. {
  40164. backgroundColourId = 0x1000b00, /**< The background colour to fill the box with. */
  40165. textColourId = 0x1000a00, /**< The colour for the text in the box. */
  40166. outlineColourId = 0x1000c00, /**< The colour for an outline around the box. */
  40167. buttonColourId = 0x1000d00, /**< The base colour for the button (a LookAndFeel class will probably use variations on this). */
  40168. arrowColourId = 0x1000e00, /**< The colour for the arrow shape that pops up the menu */
  40169. };
  40170. /** @internal */
  40171. void labelTextChanged (Label*);
  40172. /** @internal */
  40173. void enablementChanged();
  40174. /** @internal */
  40175. void colourChanged();
  40176. /** @internal */
  40177. void focusGained (Component::FocusChangeType cause);
  40178. /** @internal */
  40179. void focusLost (Component::FocusChangeType cause);
  40180. /** @internal */
  40181. void handleAsyncUpdate();
  40182. /** @internal */
  40183. const String getTooltip() { return label->getTooltip(); }
  40184. /** @internal */
  40185. void mouseDown (const MouseEvent&);
  40186. /** @internal */
  40187. void mouseDrag (const MouseEvent&);
  40188. /** @internal */
  40189. void mouseUp (const MouseEvent&);
  40190. /** @internal */
  40191. void lookAndFeelChanged();
  40192. /** @internal */
  40193. void paint (Graphics&);
  40194. /** @internal */
  40195. void resized();
  40196. /** @internal */
  40197. bool keyStateChanged (bool isKeyDown);
  40198. /** @internal */
  40199. bool keyPressed (const KeyPress&);
  40200. /** @internal */
  40201. void valueChanged (Value&);
  40202. private:
  40203. struct ItemInfo
  40204. {
  40205. ItemInfo (const String& name, int itemId, bool isEnabled, bool isHeading);
  40206. bool isSeparator() const noexcept;
  40207. bool isRealItem() const noexcept;
  40208. String name;
  40209. int itemId;
  40210. bool isEnabled : 1, isHeading : 1;
  40211. };
  40212. OwnedArray <ItemInfo> items;
  40213. Value currentId;
  40214. int lastCurrentId;
  40215. bool isButtonDown, separatorPending, menuActive, textIsCustom;
  40216. ListenerList <Listener> listeners;
  40217. ScopedPointer<Label> label;
  40218. String textWhenNothingSelected, noChoicesMessage;
  40219. ItemInfo* getItemForId (int itemId) const noexcept;
  40220. ItemInfo* getItemForIndex (int index) const noexcept;
  40221. bool selectIfEnabled (int index);
  40222. static void popupMenuFinishedCallback (int, ComboBox*);
  40223. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComboBox);
  40224. };
  40225. /** This typedef is just for compatibility with old code - newer code should use the ComboBox::Listener class directly. */
  40226. typedef ComboBox::Listener ComboBoxListener;
  40227. #if JUCE_VC6
  40228. #undef Listener
  40229. #endif
  40230. #endif // __JUCE_COMBOBOX_JUCEHEADER__
  40231. /*** End of inlined file: juce_ComboBox.h ***/
  40232. #endif
  40233. #ifndef __JUCE_IMAGECOMPONENT_JUCEHEADER__
  40234. /*** Start of inlined file: juce_ImageComponent.h ***/
  40235. #ifndef __JUCE_IMAGECOMPONENT_JUCEHEADER__
  40236. #define __JUCE_IMAGECOMPONENT_JUCEHEADER__
  40237. /**
  40238. A component that simply displays an image.
  40239. Use setImage to give it an image, and it'll display it - simple as that!
  40240. */
  40241. class JUCE_API ImageComponent : public Component,
  40242. public SettableTooltipClient
  40243. {
  40244. public:
  40245. /** Creates an ImageComponent. */
  40246. ImageComponent (const String& componentName = String::empty);
  40247. /** Destructor. */
  40248. ~ImageComponent();
  40249. /** Sets the image that should be displayed. */
  40250. void setImage (const Image& newImage);
  40251. /** Sets the image that should be displayed, and its placement within the component. */
  40252. void setImage (const Image& newImage,
  40253. const RectanglePlacement& placementToUse);
  40254. /** Returns the current image. */
  40255. const Image& getImage() const;
  40256. /** Sets the method of positioning that will be used to fit the image within the component's bounds.
  40257. By default the positioning is centred, and will fit the image inside the component's bounds
  40258. whilst keeping its aspect ratio correct, but you can change it to whatever layout you need.
  40259. */
  40260. void setImagePlacement (const RectanglePlacement& newPlacement);
  40261. /** Returns the current image placement. */
  40262. const RectanglePlacement getImagePlacement() const;
  40263. /** @internal */
  40264. void paint (Graphics& g);
  40265. private:
  40266. Image image;
  40267. RectanglePlacement placement;
  40268. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImageComponent);
  40269. };
  40270. #endif // __JUCE_IMAGECOMPONENT_JUCEHEADER__
  40271. /*** End of inlined file: juce_ImageComponent.h ***/
  40272. #endif
  40273. #ifndef __JUCE_LABEL_JUCEHEADER__
  40274. #endif
  40275. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  40276. #endif
  40277. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  40278. /*** Start of inlined file: juce_ProgressBar.h ***/
  40279. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  40280. #define __JUCE_PROGRESSBAR_JUCEHEADER__
  40281. /**
  40282. A progress bar component.
  40283. To use this, just create one and make it visible. It'll run its own timer
  40284. to keep an eye on a variable that you give it, and will automatically
  40285. redraw itself when the variable changes.
  40286. For an easy way of running a background task with a dialog box showing its
  40287. progress, see the ThreadWithProgressWindow class.
  40288. @see ThreadWithProgressWindow
  40289. */
  40290. class JUCE_API ProgressBar : public Component,
  40291. public SettableTooltipClient,
  40292. private Timer
  40293. {
  40294. public:
  40295. /** Creates a ProgressBar.
  40296. @param progress pass in a reference to a double that you're going to
  40297. update with your task's progress. The ProgressBar will
  40298. monitor the value of this variable and will redraw itself
  40299. when the value changes. The range is from 0 to 1.0. Obviously
  40300. you'd better be careful not to delete this variable while the
  40301. ProgressBar still exists!
  40302. */
  40303. explicit ProgressBar (double& progress);
  40304. /** Destructor. */
  40305. ~ProgressBar();
  40306. /** Turns the percentage display on or off.
  40307. By default this is on, and the progress bar will display a text string showing
  40308. its current percentage.
  40309. */
  40310. void setPercentageDisplay (bool shouldDisplayPercentage);
  40311. /** Gives the progress bar a string to display inside it.
  40312. If you call this, it will turn off the percentage display.
  40313. @see setPercentageDisplay
  40314. */
  40315. void setTextToDisplay (const String& text);
  40316. /** A set of colour IDs to use to change the colour of various aspects of the bar.
  40317. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  40318. methods.
  40319. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  40320. */
  40321. enum ColourIds
  40322. {
  40323. backgroundColourId = 0x1001900, /**< The background colour, behind the bar. */
  40324. foregroundColourId = 0x1001a00, /**< The colour to use to draw the bar itself. LookAndFeel
  40325. classes will probably use variations on this colour. */
  40326. };
  40327. protected:
  40328. /** @internal */
  40329. void paint (Graphics& g);
  40330. /** @internal */
  40331. void lookAndFeelChanged();
  40332. /** @internal */
  40333. void visibilityChanged();
  40334. /** @internal */
  40335. void colourChanged();
  40336. private:
  40337. double& progress;
  40338. double currentValue;
  40339. bool displayPercentage;
  40340. String displayedMessage, currentMessage;
  40341. uint32 lastCallbackTime;
  40342. void timerCallback();
  40343. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProgressBar);
  40344. };
  40345. #endif // __JUCE_PROGRESSBAR_JUCEHEADER__
  40346. /*** End of inlined file: juce_ProgressBar.h ***/
  40347. #endif
  40348. #ifndef __JUCE_SLIDER_JUCEHEADER__
  40349. /*** Start of inlined file: juce_Slider.h ***/
  40350. #ifndef __JUCE_SLIDER_JUCEHEADER__
  40351. #define __JUCE_SLIDER_JUCEHEADER__
  40352. #if JUCE_VC6
  40353. #define Listener LabelListener
  40354. #endif
  40355. /**
  40356. A slider control for changing a value.
  40357. The slider can be horizontal, vertical, or rotary, and can optionally have
  40358. a text-box inside it to show an editable display of the current value.
  40359. To use it, create a Slider object and use the setSliderStyle() method
  40360. to set up the type you want. To set up the text-entry box, use setTextBoxStyle().
  40361. To define the values that it can be set to, see the setRange() and setValue() methods.
  40362. There are also lots of custom tweaks you can do by subclassing and overriding
  40363. some of the virtual methods, such as changing the scaling, changing the format of
  40364. the text display, custom ways of limiting the values, etc.
  40365. You can register Slider::Listener objects with a slider, and they'll be called when
  40366. the value changes.
  40367. @see Slider::Listener
  40368. */
  40369. class JUCE_API Slider : public Component,
  40370. public SettableTooltipClient,
  40371. public AsyncUpdater,
  40372. public ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  40373. public LabelListener,
  40374. public ValueListener
  40375. {
  40376. public:
  40377. /** Creates a slider.
  40378. When created, you'll need to set up the slider's style and range with setSliderStyle(),
  40379. setRange(), etc.
  40380. */
  40381. explicit Slider (const String& componentName = String::empty);
  40382. /** Destructor. */
  40383. ~Slider();
  40384. /** The types of slider available.
  40385. @see setSliderStyle, setRotaryParameters
  40386. */
  40387. enum SliderStyle
  40388. {
  40389. LinearHorizontal, /**< A traditional horizontal slider. */
  40390. LinearVertical, /**< A traditional vertical slider. */
  40391. LinearBar, /**< A horizontal bar slider with the text label drawn on top of it. */
  40392. Rotary, /**< A rotary control that you move by dragging the mouse in a circular motion, like a knob.
  40393. @see setRotaryParameters */
  40394. RotaryHorizontalDrag, /**< A rotary control that you move by dragging the mouse left-to-right.
  40395. @see setRotaryParameters */
  40396. RotaryVerticalDrag, /**< A rotary control that you move by dragging the mouse up-and-down.
  40397. @see setRotaryParameters */
  40398. IncDecButtons, /**< A pair of buttons that increment or decrement the slider's value by the increment set in setRange(). */
  40399. TwoValueHorizontal, /**< A horizontal slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  40400. @see setMinValue, setMaxValue */
  40401. TwoValueVertical, /**< A vertical slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  40402. @see setMinValue, setMaxValue */
  40403. ThreeValueHorizontal, /**< A horizontal slider that has three thumbs instead of one, so it can show a minimum and maximum
  40404. value, with the current value being somewhere between them.
  40405. @see setMinValue, setMaxValue */
  40406. ThreeValueVertical, /**< A vertical slider that has three thumbs instead of one, so it can show a minimum and maximum
  40407. value, with the current value being somewhere between them.
  40408. @see setMinValue, setMaxValue */
  40409. };
  40410. /** Changes the type of slider interface being used.
  40411. @param newStyle the type of interface
  40412. @see setRotaryParameters, setVelocityBasedMode,
  40413. */
  40414. void setSliderStyle (SliderStyle newStyle);
  40415. /** Returns the slider's current style.
  40416. @see setSliderStyle
  40417. */
  40418. SliderStyle getSliderStyle() const noexcept { return style; }
  40419. /** Changes the properties of a rotary slider.
  40420. @param startAngleRadians the angle (in radians, clockwise from the top) at which
  40421. the slider's minimum value is represented
  40422. @param endAngleRadians the angle (in radians, clockwise from the top) at which
  40423. the slider's maximum value is represented. This must be
  40424. greater than startAngleRadians
  40425. @param stopAtEnd if true, then when the slider is dragged around past the
  40426. minimum or maximum, it'll stop there; if false, it'll wrap
  40427. back to the opposite value
  40428. */
  40429. void setRotaryParameters (float startAngleRadians,
  40430. float endAngleRadians,
  40431. bool stopAtEnd);
  40432. /** Sets the distance the mouse has to move to drag the slider across
  40433. the full extent of its range.
  40434. This only applies when in modes like RotaryHorizontalDrag, where it's using
  40435. relative mouse movements to adjust the slider.
  40436. */
  40437. void setMouseDragSensitivity (int distanceForFullScaleDrag);
  40438. /** Returns the current sensitivity value set by setMouseDragSensitivity(). */
  40439. int getMouseDragSensitivity() const noexcept { return pixelsForFullDragExtent; }
  40440. /** Changes the way the the mouse is used when dragging the slider.
  40441. If true, this will turn on velocity-sensitive dragging, so that
  40442. the faster the mouse moves, the bigger the movement to the slider. This
  40443. helps when making accurate adjustments if the slider's range is quite large.
  40444. If false, the slider will just try to snap to wherever the mouse is.
  40445. */
  40446. void setVelocityBasedMode (bool isVelocityBased);
  40447. /** Returns true if velocity-based mode is active.
  40448. @see setVelocityBasedMode
  40449. */
  40450. bool getVelocityBasedMode() const noexcept { return isVelocityBased; }
  40451. /** Changes aspects of the scaling used when in velocity-sensitive mode.
  40452. These apply when you've used setVelocityBasedMode() to turn on velocity mode,
  40453. or if you're holding down ctrl.
  40454. @param sensitivity higher values than 1.0 increase the range of acceleration used
  40455. @param threshold the minimum number of pixels that the mouse needs to move for it
  40456. to be treated as a movement
  40457. @param offset values greater than 0.0 increase the minimum speed that will be used when
  40458. the threshold is reached
  40459. @param userCanPressKeyToSwapMode if true, then the user can hold down the ctrl or command
  40460. key to toggle velocity-sensitive mode
  40461. */
  40462. void setVelocityModeParameters (double sensitivity = 1.0,
  40463. int threshold = 1,
  40464. double offset = 0.0,
  40465. bool userCanPressKeyToSwapMode = true);
  40466. /** Returns the velocity sensitivity setting.
  40467. @see setVelocityModeParameters
  40468. */
  40469. double getVelocitySensitivity() const noexcept { return velocityModeSensitivity; }
  40470. /** Returns the velocity threshold setting.
  40471. @see setVelocityModeParameters
  40472. */
  40473. int getVelocityThreshold() const noexcept { return velocityModeThreshold; }
  40474. /** Returns the velocity offset setting.
  40475. @see setVelocityModeParameters
  40476. */
  40477. double getVelocityOffset() const noexcept { return velocityModeOffset; }
  40478. /** Returns the velocity user key setting.
  40479. @see setVelocityModeParameters
  40480. */
  40481. bool getVelocityModeIsSwappable() const noexcept { return userKeyOverridesVelocity; }
  40482. /** Sets up a skew factor to alter the way values are distributed.
  40483. You may want to use a range of values on the slider where more accuracy
  40484. is required towards one end of the range, so this will logarithmically
  40485. spread the values across the length of the slider.
  40486. If the factor is < 1.0, the lower end of the range will fill more of the
  40487. slider's length; if the factor is > 1.0, the upper end of the range
  40488. will be expanded instead. A factor of 1.0 doesn't skew it at all.
  40489. To set the skew position by using a mid-point, use the setSkewFactorFromMidPoint()
  40490. method instead.
  40491. @see getSkewFactor, setSkewFactorFromMidPoint
  40492. */
  40493. void setSkewFactor (double factor);
  40494. /** Sets up a skew factor to alter the way values are distributed.
  40495. This allows you to specify the slider value that should appear in the
  40496. centre of the slider's visible range.
  40497. @see setSkewFactor, getSkewFactor
  40498. */
  40499. void setSkewFactorFromMidPoint (double sliderValueToShowAtMidPoint);
  40500. /** Returns the current skew factor.
  40501. See setSkewFactor for more info.
  40502. @see setSkewFactor, setSkewFactorFromMidPoint
  40503. */
  40504. double getSkewFactor() const noexcept { return skewFactor; }
  40505. /** Used by setIncDecButtonsMode().
  40506. */
  40507. enum IncDecButtonMode
  40508. {
  40509. incDecButtonsNotDraggable,
  40510. incDecButtonsDraggable_AutoDirection,
  40511. incDecButtonsDraggable_Horizontal,
  40512. incDecButtonsDraggable_Vertical
  40513. };
  40514. /** When the style is IncDecButtons, this lets you turn on a mode where the mouse
  40515. can be dragged on the buttons to drag the values.
  40516. By default this is turned off. When enabled, clicking on the buttons still works
  40517. them as normal, but by holding down the mouse on a button and dragging it a little
  40518. distance, it flips into a mode where the value can be dragged. The drag direction can
  40519. either be set explicitly to be vertical or horizontal, or can be set to
  40520. incDecButtonsDraggable_AutoDirection so that it depends on whether the buttons
  40521. are side-by-side or above each other.
  40522. */
  40523. void setIncDecButtonsMode (IncDecButtonMode mode);
  40524. /** The position of the slider's text-entry box.
  40525. @see setTextBoxStyle
  40526. */
  40527. enum TextEntryBoxPosition
  40528. {
  40529. NoTextBox, /**< Doesn't display a text box. */
  40530. TextBoxLeft, /**< Puts the text box to the left of the slider, vertically centred. */
  40531. TextBoxRight, /**< Puts the text box to the right of the slider, vertically centred. */
  40532. TextBoxAbove, /**< Puts the text box above the slider, horizontally centred. */
  40533. TextBoxBelow /**< Puts the text box below the slider, horizontally centred. */
  40534. };
  40535. /** Changes the location and properties of the text-entry box.
  40536. @param newPosition where it should go (or NoTextBox to not have one at all)
  40537. @param isReadOnly if true, it's a read-only display
  40538. @param textEntryBoxWidth the width of the text-box in pixels. Make sure this leaves enough
  40539. room for the slider as well!
  40540. @param textEntryBoxHeight the height of the text-box in pixels. Make sure this leaves enough
  40541. room for the slider as well!
  40542. @see setTextBoxIsEditable, getValueFromText, getTextFromValue
  40543. */
  40544. void setTextBoxStyle (TextEntryBoxPosition newPosition,
  40545. bool isReadOnly,
  40546. int textEntryBoxWidth,
  40547. int textEntryBoxHeight);
  40548. /** Returns the status of the text-box.
  40549. @see setTextBoxStyle
  40550. */
  40551. const TextEntryBoxPosition getTextBoxPosition() const noexcept { return textBoxPos; }
  40552. /** Returns the width used for the text-box.
  40553. @see setTextBoxStyle
  40554. */
  40555. int getTextBoxWidth() const noexcept { return textBoxWidth; }
  40556. /** Returns the height used for the text-box.
  40557. @see setTextBoxStyle
  40558. */
  40559. int getTextBoxHeight() const noexcept { return textBoxHeight; }
  40560. /** Makes the text-box editable.
  40561. By default this is true, and the user can enter values into the textbox,
  40562. but it can be turned off if that's not suitable.
  40563. @see setTextBoxStyle, getValueFromText, getTextFromValue
  40564. */
  40565. void setTextBoxIsEditable (bool shouldBeEditable);
  40566. /** Returns true if the text-box is read-only.
  40567. @see setTextBoxStyle
  40568. */
  40569. bool isTextBoxEditable() const { return editableText; }
  40570. /** If the text-box is editable, this will give it the focus so that the user can
  40571. type directly into it.
  40572. This is basically the effect as the user clicking on it.
  40573. */
  40574. void showTextBox();
  40575. /** If the text-box currently has focus and is being edited, this resets it and takes keyboard
  40576. focus away from it.
  40577. @param discardCurrentEditorContents if true, the slider's value will be left
  40578. unchanged; if false, the current contents of the
  40579. text editor will be used to set the slider position
  40580. before it is hidden.
  40581. */
  40582. void hideTextBox (bool discardCurrentEditorContents);
  40583. /** Changes the slider's current value.
  40584. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  40585. that are registered, and will synchronously call the valueChanged() method in case subclasses
  40586. want to handle it.
  40587. @param newValue the new value to set - this will be restricted by the
  40588. minimum and maximum range, and will be snapped to the
  40589. nearest interval if one has been set
  40590. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  40591. any Slider::Listeners or the valueChanged() method
  40592. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  40593. synchronously; if false, it will be asynchronous
  40594. */
  40595. void setValue (double newValue,
  40596. bool sendUpdateMessage = true,
  40597. bool sendMessageSynchronously = false);
  40598. /** Returns the slider's current value. */
  40599. double getValue() const;
  40600. /** Returns the Value object that represents the slider's current position.
  40601. You can use this Value object to connect the slider's position to external values or setters,
  40602. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  40603. your own Value object.
  40604. @see Value, getMaxValue, getMinValueObject
  40605. */
  40606. Value& getValueObject() { return currentValue; }
  40607. /** Sets the limits that the slider's value can take.
  40608. @param newMinimum the lowest value allowed
  40609. @param newMaximum the highest value allowed
  40610. @param newInterval the steps in which the value is allowed to increase - if this
  40611. is not zero, the value will always be (newMinimum + (newInterval * an integer)).
  40612. */
  40613. void setRange (double newMinimum,
  40614. double newMaximum,
  40615. double newInterval = 0);
  40616. /** Returns the current maximum value.
  40617. @see setRange
  40618. */
  40619. double getMaximum() const { return maximum; }
  40620. /** Returns the current minimum value.
  40621. @see setRange
  40622. */
  40623. double getMinimum() const { return minimum; }
  40624. /** Returns the current step-size for values.
  40625. @see setRange
  40626. */
  40627. double getInterval() const { return interval; }
  40628. /** For a slider with two or three thumbs, this returns the lower of its values.
  40629. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  40630. A slider with three values also uses the normal getValue() and setValue() methods to
  40631. control the middle value.
  40632. @see setMinValue, getMaxValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  40633. */
  40634. double getMinValue() const;
  40635. /** For a slider with two or three thumbs, this returns the lower of its values.
  40636. You can use this Value object to connect the slider's position to external values or setters,
  40637. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  40638. your own Value object.
  40639. @see Value, getMinValue, getMaxValueObject
  40640. */
  40641. Value& getMinValueObject() noexcept { return valueMin; }
  40642. /** For a slider with two or three thumbs, this sets the lower of its values.
  40643. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  40644. that are registered, and will synchronously call the valueChanged() method in case subclasses
  40645. want to handle it.
  40646. @param newValue the new value to set - this will be restricted by the
  40647. minimum and maximum range, and will be snapped to the nearest
  40648. interval if one has been set.
  40649. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  40650. any Slider::Listeners or the valueChanged() method
  40651. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  40652. synchronously; if false, it will be asynchronous
  40653. @param allowNudgingOfOtherValues if false, this value will be restricted to being below the
  40654. max value (in a two-value slider) or the mid value (in a three-value
  40655. slider). If false, then if this value goes beyond those values,
  40656. it will push them along with it.
  40657. @see getMinValue, setMaxValue, setValue
  40658. */
  40659. void setMinValue (double newValue,
  40660. bool sendUpdateMessage = true,
  40661. bool sendMessageSynchronously = false,
  40662. bool allowNudgingOfOtherValues = false);
  40663. /** For a slider with two or three thumbs, this returns the higher of its values.
  40664. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  40665. A slider with three values also uses the normal getValue() and setValue() methods to
  40666. control the middle value.
  40667. @see getMinValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  40668. */
  40669. double getMaxValue() const;
  40670. /** For a slider with two or three thumbs, this returns the higher of its values.
  40671. You can use this Value object to connect the slider's position to external values or setters,
  40672. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  40673. your own Value object.
  40674. @see Value, getMaxValue, getMinValueObject
  40675. */
  40676. Value& getMaxValueObject() noexcept { return valueMax; }
  40677. /** For a slider with two or three thumbs, this sets the lower of its values.
  40678. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  40679. that are registered, and will synchronously call the valueChanged() method in case subclasses
  40680. want to handle it.
  40681. @param newValue the new value to set - this will be restricted by the
  40682. minimum and maximum range, and will be snapped to the nearest
  40683. interval if one has been set.
  40684. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  40685. any Slider::Listeners or the valueChanged() method
  40686. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  40687. synchronously; if false, it will be asynchronous
  40688. @param allowNudgingOfOtherValues if false, this value will be restricted to being above the
  40689. min value (in a two-value slider) or the mid value (in a three-value
  40690. slider). If false, then if this value goes beyond those values,
  40691. it will push them along with it.
  40692. @see getMaxValue, setMinValue, setValue
  40693. */
  40694. void setMaxValue (double newValue,
  40695. bool sendUpdateMessage = true,
  40696. bool sendMessageSynchronously = false,
  40697. bool allowNudgingOfOtherValues = false);
  40698. /** For a slider with two or three thumbs, this sets the minimum and maximum thumb positions.
  40699. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  40700. that are registered, and will synchronously call the valueChanged() method in case subclasses
  40701. want to handle it.
  40702. @param newMinValue the new minimum value to set - this will be snapped to the
  40703. nearest interval if one has been set.
  40704. @param newMaxValue the new minimum value to set - this will be snapped to the
  40705. nearest interval if one has been set.
  40706. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  40707. any Slider::Listeners or the valueChanged() method
  40708. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  40709. synchronously; if false, it will be asynchronous
  40710. @see setMaxValue, setMinValue, setValue
  40711. */
  40712. void setMinAndMaxValues (double newMinValue, double newMaxValue,
  40713. bool sendUpdateMessage = true,
  40714. bool sendMessageSynchronously = false);
  40715. /** A class for receiving callbacks from a Slider.
  40716. To be told when a slider's value changes, you can register a Slider::Listener
  40717. object using Slider::addListener().
  40718. @see Slider::addListener, Slider::removeListener
  40719. */
  40720. class JUCE_API Listener
  40721. {
  40722. public:
  40723. /** Destructor. */
  40724. virtual ~Listener() {}
  40725. /** Called when the slider's value is changed.
  40726. This may be caused by dragging it, or by typing in its text entry box,
  40727. or by a call to Slider::setValue().
  40728. You can find out the new value using Slider::getValue().
  40729. @see Slider::valueChanged
  40730. */
  40731. virtual void sliderValueChanged (Slider* slider) = 0;
  40732. /** Called when the slider is about to be dragged.
  40733. This is called when a drag begins, then it's followed by multiple calls
  40734. to sliderValueChanged(), and then sliderDragEnded() is called after the
  40735. user lets go.
  40736. @see sliderDragEnded, Slider::startedDragging
  40737. */
  40738. virtual void sliderDragStarted (Slider* slider);
  40739. /** Called after a drag operation has finished.
  40740. @see sliderDragStarted, Slider::stoppedDragging
  40741. */
  40742. virtual void sliderDragEnded (Slider* slider);
  40743. };
  40744. /** Adds a listener to be called when this slider's value changes. */
  40745. void addListener (Listener* listener);
  40746. /** Removes a previously-registered listener. */
  40747. void removeListener (Listener* listener);
  40748. /** This lets you choose whether double-clicking moves the slider to a given position.
  40749. By default this is turned off, but it's handy if you want a double-click to act
  40750. as a quick way of resetting a slider. Just pass in the value you want it to
  40751. go to when double-clicked.
  40752. @see getDoubleClickReturnValue
  40753. */
  40754. void setDoubleClickReturnValue (bool isDoubleClickEnabled,
  40755. double valueToSetOnDoubleClick);
  40756. /** Returns the values last set by setDoubleClickReturnValue() method.
  40757. Sets isEnabled to true if double-click is enabled, and returns the value
  40758. that was set.
  40759. @see setDoubleClickReturnValue
  40760. */
  40761. double getDoubleClickReturnValue (bool& isEnabled) const;
  40762. /** Tells the slider whether to keep sending change messages while the user
  40763. is dragging the slider.
  40764. If set to true, a change message will only be sent when the user has
  40765. dragged the slider and let go. If set to false (the default), then messages
  40766. will be continuously sent as they drag it while the mouse button is still
  40767. held down.
  40768. */
  40769. void setChangeNotificationOnlyOnRelease (bool onlyNotifyOnRelease);
  40770. /** This lets you change whether the slider thumb jumps to the mouse position
  40771. when you click.
  40772. By default, this is true. If it's false, then the slider moves with relative
  40773. motion when you drag it.
  40774. This only applies to linear bars, and won't affect two- or three- value
  40775. sliders.
  40776. */
  40777. void setSliderSnapsToMousePosition (bool shouldSnapToMouse);
  40778. /** If enabled, this gives the slider a pop-up bubble which appears while the
  40779. slider is being dragged.
  40780. This can be handy if your slider doesn't have a text-box, so that users can
  40781. see the value just when they're changing it.
  40782. If you pass a component as the parentComponentToUse parameter, the pop-up
  40783. bubble will be added as a child of that component when it's needed. If you
  40784. pass 0, the pop-up will be placed on the desktop instead (note that it's a
  40785. transparent window, so if you're using an OS that can't do transparent windows
  40786. you'll have to add it to a parent component instead).
  40787. */
  40788. void setPopupDisplayEnabled (bool isEnabled,
  40789. Component* parentComponentToUse);
  40790. /** If this is set to true, then right-clicking on the slider will pop-up
  40791. a menu to let the user change the way it works.
  40792. By default this is turned off, but when turned on, the menu will include
  40793. things like velocity sensitivity, and for rotary sliders, whether they
  40794. use a linear or rotary mouse-drag to move them.
  40795. */
  40796. void setPopupMenuEnabled (bool menuEnabled);
  40797. /** This can be used to stop the mouse scroll-wheel from moving the slider.
  40798. By default it's enabled.
  40799. */
  40800. void setScrollWheelEnabled (bool enabled);
  40801. /** Returns a number to indicate which thumb is currently being dragged by the
  40802. mouse.
  40803. This will return 0 for the main thumb, 1 for the minimum-value thumb, 2 for
  40804. the maximum-value thumb, or -1 if none is currently down.
  40805. */
  40806. int getThumbBeingDragged() const noexcept { return sliderBeingDragged; }
  40807. /** Callback to indicate that the user is about to start dragging the slider.
  40808. @see Slider::Listener::sliderDragStarted
  40809. */
  40810. virtual void startedDragging();
  40811. /** Callback to indicate that the user has just stopped dragging the slider.
  40812. @see Slider::Listener::sliderDragEnded
  40813. */
  40814. virtual void stoppedDragging();
  40815. /** Callback to indicate that the user has just moved the slider.
  40816. @see Slider::Listener::sliderValueChanged
  40817. */
  40818. virtual void valueChanged();
  40819. /** Subclasses can override this to convert a text string to a value.
  40820. When the user enters something into the text-entry box, this method is
  40821. called to convert it to a value.
  40822. The default routine just tries to convert it to a double.
  40823. @see getTextFromValue
  40824. */
  40825. virtual double getValueFromText (const String& text);
  40826. /** Turns the slider's current value into a text string.
  40827. Subclasses can override this to customise the formatting of the text-entry box.
  40828. The default implementation just turns the value into a string, using
  40829. a number of decimal places based on the range interval. If a suffix string
  40830. has been set using setTextValueSuffix(), this will be appended to the text.
  40831. @see getValueFromText
  40832. */
  40833. virtual const String getTextFromValue (double value);
  40834. /** Sets a suffix to append to the end of the numeric value when it's displayed as
  40835. a string.
  40836. This is used by the default implementation of getTextFromValue(), and is just
  40837. appended to the numeric value. For more advanced formatting, you can override
  40838. getTextFromValue() and do something else.
  40839. */
  40840. void setTextValueSuffix (const String& suffix);
  40841. /** Returns the suffix that was set by setTextValueSuffix(). */
  40842. String getTextValueSuffix() const;
  40843. /** Allows a user-defined mapping of distance along the slider to its value.
  40844. The default implementation for this performs the skewing operation that
  40845. can be set up in the setSkewFactor() method. Override it if you need
  40846. some kind of custom mapping instead, but make sure you also implement the
  40847. inverse function in valueToProportionOfLength().
  40848. @param proportion a value 0 to 1.0, indicating a distance along the slider
  40849. @returns the slider value that is represented by this position
  40850. @see valueToProportionOfLength
  40851. */
  40852. virtual double proportionOfLengthToValue (double proportion);
  40853. /** Allows a user-defined mapping of value to the position of the slider along its length.
  40854. The default implementation for this performs the skewing operation that
  40855. can be set up in the setSkewFactor() method. Override it if you need
  40856. some kind of custom mapping instead, but make sure you also implement the
  40857. inverse function in proportionOfLengthToValue().
  40858. @param value a valid slider value, between the range of values specified in
  40859. setRange()
  40860. @returns a value 0 to 1.0 indicating the distance along the slider that
  40861. represents this value
  40862. @see proportionOfLengthToValue
  40863. */
  40864. virtual double valueToProportionOfLength (double value);
  40865. /** Returns the X or Y coordinate of a value along the slider's length.
  40866. If the slider is horizontal, this will be the X coordinate of the given
  40867. value, relative to the left of the slider. If it's vertical, then this will
  40868. be the Y coordinate, relative to the top of the slider.
  40869. If the slider is rotary, this will throw an assertion and return 0. If the
  40870. value is out-of-range, it will be constrained to the length of the slider.
  40871. */
  40872. float getPositionOfValue (double value);
  40873. /** This can be overridden to allow the slider to snap to user-definable values.
  40874. If overridden, it will be called when the user tries to move the slider to
  40875. a given position, and allows a subclass to sanity-check this value, possibly
  40876. returning a different value to use instead.
  40877. @param attemptedValue the value the user is trying to enter
  40878. @param userIsDragging true if the user is dragging with the mouse; false if
  40879. they are entering the value using the text box
  40880. @returns the value to use instead
  40881. */
  40882. virtual double snapValue (double attemptedValue, bool userIsDragging);
  40883. /** This can be called to force the text box to update its contents.
  40884. (Not normally needed, as this is done automatically).
  40885. */
  40886. void updateText();
  40887. /** True if the slider moves horizontally. */
  40888. bool isHorizontal() const;
  40889. /** True if the slider moves vertically. */
  40890. bool isVertical() const;
  40891. /** A set of colour IDs to use to change the colour of various aspects of the slider.
  40892. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  40893. methods.
  40894. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  40895. */
  40896. enum ColourIds
  40897. {
  40898. backgroundColourId = 0x1001200, /**< A colour to use to fill the slider's background. */
  40899. thumbColourId = 0x1001300, /**< The colour to draw the thumb with. It's up to the look
  40900. and feel class how this is used. */
  40901. trackColourId = 0x1001310, /**< The colour to draw the groove that the thumb moves along. */
  40902. rotarySliderFillColourId = 0x1001311, /**< For rotary sliders, this colour fills the outer curve. */
  40903. rotarySliderOutlineColourId = 0x1001312, /**< For rotary sliders, this colour is used to draw the outer curve's outline. */
  40904. textBoxTextColourId = 0x1001400, /**< The colour for the text in the text-editor box used for editing the value. */
  40905. textBoxBackgroundColourId = 0x1001500, /**< The background colour for the text-editor box. */
  40906. textBoxHighlightColourId = 0x1001600, /**< The text highlight colour for the text-editor box. */
  40907. textBoxOutlineColourId = 0x1001700 /**< The colour to use for a border around the text-editor box. */
  40908. };
  40909. protected:
  40910. /** @internal */
  40911. void labelTextChanged (Label*);
  40912. /** @internal */
  40913. void paint (Graphics& g);
  40914. /** @internal */
  40915. void resized();
  40916. /** @internal */
  40917. void mouseDown (const MouseEvent& e);
  40918. /** @internal */
  40919. void mouseUp (const MouseEvent& e);
  40920. /** @internal */
  40921. void mouseDrag (const MouseEvent& e);
  40922. /** @internal */
  40923. void mouseDoubleClick (const MouseEvent& e);
  40924. /** @internal */
  40925. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  40926. /** @internal */
  40927. void modifierKeysChanged (const ModifierKeys& modifiers);
  40928. /** @internal */
  40929. void buttonClicked (Button* button);
  40930. /** @internal */
  40931. void lookAndFeelChanged();
  40932. /** @internal */
  40933. void enablementChanged();
  40934. /** @internal */
  40935. void focusOfChildComponentChanged (FocusChangeType cause);
  40936. /** @internal */
  40937. void handleAsyncUpdate();
  40938. /** @internal */
  40939. void colourChanged();
  40940. /** @internal */
  40941. void valueChanged (Value& value);
  40942. /** Returns the best number of decimal places to use when displaying numbers.
  40943. This is calculated from the slider's interval setting.
  40944. */
  40945. int getNumDecimalPlacesToDisplay() const noexcept { return numDecimalPlaces; }
  40946. private:
  40947. ListenerList <Listener> listeners;
  40948. Value currentValue, valueMin, valueMax;
  40949. double lastCurrentValue, lastValueMin, lastValueMax;
  40950. double minimum, maximum, interval, doubleClickReturnValue;
  40951. double valueWhenLastDragged, valueOnMouseDown, skewFactor, lastAngle;
  40952. double velocityModeSensitivity, velocityModeOffset, minMaxDiff;
  40953. int velocityModeThreshold;
  40954. float rotaryStart, rotaryEnd;
  40955. int numDecimalPlaces;
  40956. Point<int> mousePosWhenLastDragged;
  40957. int mouseDragStartX, mouseDragStartY;
  40958. int sliderRegionStart, sliderRegionSize;
  40959. int sliderBeingDragged;
  40960. int pixelsForFullDragExtent;
  40961. Rectangle<int> sliderRect;
  40962. String textSuffix;
  40963. SliderStyle style;
  40964. TextEntryBoxPosition textBoxPos;
  40965. int textBoxWidth, textBoxHeight;
  40966. IncDecButtonMode incDecButtonMode;
  40967. bool editableText : 1, doubleClickToValue : 1;
  40968. bool isVelocityBased : 1, userKeyOverridesVelocity : 1, rotaryStop : 1;
  40969. bool incDecButtonsSideBySide : 1, sendChangeOnlyOnRelease : 1, popupDisplayEnabled : 1;
  40970. bool menuEnabled : 1, menuShown : 1, mouseWasHidden : 1, incDecDragged : 1;
  40971. bool scrollWheelEnabled : 1, snapsToMousePos : 1;
  40972. ScopedPointer<Label> valueBox;
  40973. ScopedPointer<Button> incButton, decButton;
  40974. class PopupDisplayComponent;
  40975. friend class PopupDisplayComponent;
  40976. friend class ScopedPointer <PopupDisplayComponent>;
  40977. ScopedPointer <PopupDisplayComponent> popupDisplay;
  40978. Component* parentForPopupDisplay;
  40979. float getLinearSliderPos (double value);
  40980. void restoreMouseIfHidden();
  40981. void sendDragStart();
  40982. void sendDragEnd();
  40983. double constrainedValue (double value) const;
  40984. void triggerChangeMessage (bool synchronous);
  40985. bool incDecDragDirectionIsHorizontal() const;
  40986. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Slider);
  40987. };
  40988. /** This typedef is just for compatibility with old code - newer code should use the Slider::Listener class directly. */
  40989. typedef Slider::Listener SliderListener;
  40990. #if JUCE_VC6
  40991. #undef Listener
  40992. #endif
  40993. #endif // __JUCE_SLIDER_JUCEHEADER__
  40994. /*** End of inlined file: juce_Slider.h ***/
  40995. #endif
  40996. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  40997. /*** Start of inlined file: juce_TableHeaderComponent.h ***/
  40998. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  40999. #define __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  41000. /**
  41001. A component that displays a strip of column headings for a table, and allows these
  41002. to be resized, dragged around, etc.
  41003. This is just the component that goes at the top of a table. You can use it
  41004. directly for custom components, or to create a simple table, use the
  41005. TableListBox class.
  41006. To use one of these, create it and use addColumn() to add all the columns that you need.
  41007. Each column must be given a unique ID number that's used to refer to it.
  41008. @see TableListBox, TableHeaderComponent::Listener
  41009. */
  41010. class JUCE_API TableHeaderComponent : public Component,
  41011. private AsyncUpdater
  41012. {
  41013. public:
  41014. /** Creates an empty table header.
  41015. */
  41016. TableHeaderComponent();
  41017. /** Destructor. */
  41018. ~TableHeaderComponent();
  41019. /** A combination of these flags are passed into the addColumn() method to specify
  41020. the properties of a column.
  41021. */
  41022. enum ColumnPropertyFlags
  41023. {
  41024. 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. */
  41025. resizable = 2, /**< If this is set, the column can be resized by dragging it. */
  41026. draggable = 4, /**< If this is set, the column can be dragged around to change its order in the table. */
  41027. appearsOnColumnMenu = 8, /**< If this is set, the column will be shown on the pop-up menu allowing it to be hidden/shown. */
  41028. 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. */
  41029. sortedForwards = 32, /**< If this is set, the column is currently the one by which the table is sorted (forwards). */
  41030. sortedBackwards = 64, /**< If this is set, the column is currently the one by which the table is sorted (backwards). */
  41031. /** This set of default flags is used as the default parameter value in addColumn(). */
  41032. defaultFlags = (visible | resizable | draggable | appearsOnColumnMenu | sortable),
  41033. /** A quick way of combining flags for a column that's not resizable. */
  41034. notResizable = (visible | draggable | appearsOnColumnMenu | sortable),
  41035. /** A quick way of combining flags for a column that's not resizable or sortable. */
  41036. notResizableOrSortable = (visible | draggable | appearsOnColumnMenu),
  41037. /** A quick way of combining flags for a column that's not sortable. */
  41038. notSortable = (visible | resizable | draggable | appearsOnColumnMenu)
  41039. };
  41040. /** Adds a column to the table.
  41041. This will add a column, and asynchronously call the tableColumnsChanged() method of any
  41042. registered listeners.
  41043. @param columnName the name of the new column. It's ok to have two or more columns with the same name
  41044. @param columnId an ID for this column. The ID can be any number apart from 0, but every column must have
  41045. a unique ID. This is used to identify the column later on, after the user may have
  41046. changed the order that they appear in
  41047. @param width the initial width of the column, in pixels
  41048. @param maximumWidth a maximum width that the column can take when the user is resizing it. This only applies
  41049. if the 'resizable' flag is specified for this column
  41050. @param minimumWidth a minimum width that the column can take when the user is resizing it. This only applies
  41051. if the 'resizable' flag is specified for this column
  41052. @param propertyFlags a combination of some of the values from the ColumnPropertyFlags enum, to define the
  41053. properties of this column
  41054. @param insertIndex the index at which the column should be added. A value of 0 puts it at the start (left-hand side)
  41055. and -1 puts it at the end (right-hand size) of the table. Note that the index the index within
  41056. all columns, not just the index amongst those that are currently visible
  41057. */
  41058. void addColumn (const String& columnName,
  41059. int columnId,
  41060. int width,
  41061. int minimumWidth = 30,
  41062. int maximumWidth = -1,
  41063. int propertyFlags = defaultFlags,
  41064. int insertIndex = -1);
  41065. /** Removes a column with the given ID.
  41066. If there is such a column, this will asynchronously call the tableColumnsChanged() method of any
  41067. registered listeners.
  41068. */
  41069. void removeColumn (int columnIdToRemove);
  41070. /** Deletes all columns from the table.
  41071. If there are any columns to remove, this will asynchronously call the tableColumnsChanged() method of any
  41072. registered listeners.
  41073. */
  41074. void removeAllColumns();
  41075. /** Returns the number of columns in the table.
  41076. If onlyCountVisibleColumns is true, this will return the number of visible columns; otherwise it'll
  41077. return the total number of columns, including hidden ones.
  41078. @see isColumnVisible
  41079. */
  41080. int getNumColumns (bool onlyCountVisibleColumns) const;
  41081. /** Returns the name for a column.
  41082. @see setColumnName
  41083. */
  41084. String getColumnName (int columnId) const;
  41085. /** Changes the name of a column. */
  41086. void setColumnName (int columnId, const String& newName);
  41087. /** Moves a column to a different index in the table.
  41088. @param columnId the column to move
  41089. @param newVisibleIndex the target index for it, from 0 to the number of columns currently visible.
  41090. */
  41091. void moveColumn (int columnId, int newVisibleIndex);
  41092. /** Returns the width of one of the columns.
  41093. */
  41094. int getColumnWidth (int columnId) const;
  41095. /** Changes the width of a column.
  41096. This will cause an asynchronous callback to the tableColumnsResized() method of any registered listeners.
  41097. */
  41098. void setColumnWidth (int columnId, int newWidth);
  41099. /** Shows or hides a column.
  41100. This can cause an asynchronous callback to the tableColumnsChanged() method of any registered listeners.
  41101. @see isColumnVisible
  41102. */
  41103. void setColumnVisible (int columnId, bool shouldBeVisible);
  41104. /** Returns true if this column is currently visible.
  41105. @see setColumnVisible
  41106. */
  41107. bool isColumnVisible (int columnId) const;
  41108. /** Changes the column which is the sort column.
  41109. This can cause an asynchronous callback to the tableSortOrderChanged() method of any registered listeners.
  41110. If this method doesn't actually change the column ID, then no re-sort will take place (you can
  41111. call reSortTable() to force a re-sort to happen if you've modified the table's contents).
  41112. @see getSortColumnId, isSortedForwards, reSortTable
  41113. */
  41114. void setSortColumnId (int columnId, bool sortForwards);
  41115. /** Returns the column ID by which the table is currently sorted, or 0 if it is unsorted.
  41116. @see setSortColumnId, isSortedForwards
  41117. */
  41118. int getSortColumnId() const;
  41119. /** Returns true if the table is currently sorted forwards, or false if it's backwards.
  41120. @see setSortColumnId
  41121. */
  41122. bool isSortedForwards() const;
  41123. /** Triggers a re-sort of the table according to the current sort-column.
  41124. If you modifiy the table's contents, you can call this to signal that the table needs
  41125. to be re-sorted.
  41126. (This doesn't do any sorting synchronously - it just asynchronously sends a call to the
  41127. tableSortOrderChanged() method of any listeners).
  41128. */
  41129. void reSortTable();
  41130. /** Returns the total width of all the visible columns in the table.
  41131. */
  41132. int getTotalWidth() const;
  41133. /** Returns the index of a given column.
  41134. If there's no such column ID, this will return -1.
  41135. If onlyCountVisibleColumns is true, this will return the index amoungst the visible columns;
  41136. otherwise it'll return the index amongst all the columns, including any hidden ones.
  41137. */
  41138. int getIndexOfColumnId (int columnId, bool onlyCountVisibleColumns) const;
  41139. /** Returns the ID of the column at a given index.
  41140. If onlyCountVisibleColumns is true, this will count the index amoungst the visible columns;
  41141. otherwise it'll count it amongst all the columns, including any hidden ones.
  41142. If the index is out-of-range, it'll return 0.
  41143. */
  41144. int getColumnIdOfIndex (int index, bool onlyCountVisibleColumns) const;
  41145. /** Returns the rectangle containing of one of the columns.
  41146. The index is an index from 0 to the number of columns that are currently visible (hidden
  41147. ones are not counted). It returns a rectangle showing the position of the column relative
  41148. to this component's top-left. If the index is out-of-range, an empty rectangle is retrurned.
  41149. */
  41150. const Rectangle<int> getColumnPosition (int index) const;
  41151. /** Finds the column ID at a given x-position in the component.
  41152. If there is a column at this point this returns its ID, or if not, it will return 0.
  41153. */
  41154. int getColumnIdAtX (int xToFind) const;
  41155. /** If set to true, this indicates that the columns should be expanded or shrunk to fill the
  41156. entire width of the component.
  41157. By default this is disabled. Turning it on also means that when resizing a column, those
  41158. on the right will be squashed to fit.
  41159. */
  41160. void setStretchToFitActive (bool shouldStretchToFit);
  41161. /** Returns true if stretch-to-fit has been enabled.
  41162. @see setStretchToFitActive
  41163. */
  41164. bool isStretchToFitActive() const;
  41165. /** If stretch-to-fit is enabled, this will resize all the columns to make them fit into the
  41166. specified width, keeping their relative proportions the same.
  41167. If the minimum widths of the columns are too wide to fit into this space, it may
  41168. actually end up wider.
  41169. */
  41170. void resizeAllColumnsToFit (int targetTotalWidth);
  41171. /** Enables or disables the pop-up menu.
  41172. The default menu allows the user to show or hide columns. You can add custom
  41173. items to this menu by overloading the addMenuItems() and reactToMenuItem() methods.
  41174. By default the menu is enabled.
  41175. @see isPopupMenuActive, addMenuItems, reactToMenuItem
  41176. */
  41177. void setPopupMenuActive (bool hasMenu);
  41178. /** Returns true if the pop-up menu is enabled.
  41179. @see setPopupMenuActive
  41180. */
  41181. bool isPopupMenuActive() const;
  41182. /** Returns a string that encapsulates the table's current layout.
  41183. This can be restored later using restoreFromString(). It saves the order of
  41184. the columns, the currently-sorted column, and the widths.
  41185. @see restoreFromString
  41186. */
  41187. String toString() const;
  41188. /** Restores the state of the table, based on a string previously created with
  41189. toString().
  41190. @see toString
  41191. */
  41192. void restoreFromString (const String& storedVersion);
  41193. /**
  41194. Receives events from a TableHeaderComponent when columns are resized, moved, etc.
  41195. You can register one of these objects for table events using TableHeaderComponent::addListener()
  41196. and TableHeaderComponent::removeListener().
  41197. @see TableHeaderComponent
  41198. */
  41199. class JUCE_API Listener
  41200. {
  41201. public:
  41202. Listener() {}
  41203. /** Destructor. */
  41204. virtual ~Listener() {}
  41205. /** This is called when some of the table's columns are added, removed, hidden,
  41206. or rearranged.
  41207. */
  41208. virtual void tableColumnsChanged (TableHeaderComponent* tableHeader) = 0;
  41209. /** This is called when one or more of the table's columns are resized.
  41210. */
  41211. virtual void tableColumnsResized (TableHeaderComponent* tableHeader) = 0;
  41212. /** This is called when the column by which the table should be sorted is changed.
  41213. */
  41214. virtual void tableSortOrderChanged (TableHeaderComponent* tableHeader) = 0;
  41215. /** This is called when the user begins or ends dragging one of the columns around.
  41216. When the user starts dragging a column, this is called with the ID of that
  41217. column. When they finish dragging, it is called again with 0 as the ID.
  41218. */
  41219. virtual void tableColumnDraggingChanged (TableHeaderComponent* tableHeader,
  41220. int columnIdNowBeingDragged);
  41221. };
  41222. /** Adds a listener to be informed about things that happen to the header. */
  41223. void addListener (Listener* newListener);
  41224. /** Removes a previously-registered listener. */
  41225. void removeListener (Listener* listenerToRemove);
  41226. /** This can be overridden to handle a mouse-click on one of the column headers.
  41227. The default implementation will use this click to call getSortColumnId() and
  41228. change the sort order.
  41229. */
  41230. virtual void columnClicked (int columnId, const ModifierKeys& mods);
  41231. /** This can be overridden to add custom items to the pop-up menu.
  41232. If you override this, you should call the superclass's method to add its
  41233. column show/hide items, if you want them on the menu as well.
  41234. Then to handle the result, override reactToMenuItem().
  41235. @see reactToMenuItem
  41236. */
  41237. virtual void addMenuItems (PopupMenu& menu, int columnIdClicked);
  41238. /** Override this to handle any custom items that you have added to the
  41239. pop-up menu with an addMenuItems() override.
  41240. If the menuReturnId isn't one of your own custom menu items, you'll need to
  41241. call TableHeaderComponent::reactToMenuItem() to allow the base class to
  41242. handle the items that it had added.
  41243. @see addMenuItems
  41244. */
  41245. virtual void reactToMenuItem (int menuReturnId, int columnIdClicked);
  41246. /** @internal */
  41247. void paint (Graphics& g);
  41248. /** @internal */
  41249. void resized();
  41250. /** @internal */
  41251. void mouseMove (const MouseEvent&);
  41252. /** @internal */
  41253. void mouseEnter (const MouseEvent&);
  41254. /** @internal */
  41255. void mouseExit (const MouseEvent&);
  41256. /** @internal */
  41257. void mouseDown (const MouseEvent&);
  41258. /** @internal */
  41259. void mouseDrag (const MouseEvent&);
  41260. /** @internal */
  41261. void mouseUp (const MouseEvent&);
  41262. /** @internal */
  41263. const MouseCursor getMouseCursor();
  41264. /** Can be overridden for more control over the pop-up menu behaviour. */
  41265. virtual void showColumnChooserMenu (int columnIdClicked);
  41266. private:
  41267. struct ColumnInfo
  41268. {
  41269. String name;
  41270. int id, propertyFlags, width, minimumWidth, maximumWidth;
  41271. double lastDeliberateWidth;
  41272. bool isVisible() const;
  41273. };
  41274. OwnedArray <ColumnInfo> columns;
  41275. Array <Listener*> listeners;
  41276. ScopedPointer <Component> dragOverlayComp;
  41277. bool columnsChanged, columnsResized, sortChanged, menuActive, stretchToFit;
  41278. int columnIdBeingResized, columnIdBeingDragged, initialColumnWidth;
  41279. int columnIdUnderMouse, draggingColumnOffset, draggingColumnOriginalIndex, lastDeliberateWidth;
  41280. ColumnInfo* getInfoForId (int columnId) const;
  41281. int visibleIndexToTotalIndex (int visibleIndex) const;
  41282. void sendColumnsChanged();
  41283. void handleAsyncUpdate();
  41284. void beginDrag (const MouseEvent&);
  41285. void endDrag (int finalIndex);
  41286. int getResizeDraggerAt (int mouseX) const;
  41287. void updateColumnUnderMouse (int x, int y);
  41288. void resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth);
  41289. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableHeaderComponent);
  41290. };
  41291. /** This typedef is just for compatibility with old code - newer code should use the TableHeaderComponent::Listener class directly. */
  41292. typedef TableHeaderComponent::Listener TableHeaderListener;
  41293. #endif // __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  41294. /*** End of inlined file: juce_TableHeaderComponent.h ***/
  41295. #endif
  41296. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  41297. /*** Start of inlined file: juce_TableListBox.h ***/
  41298. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  41299. #define __JUCE_TABLELISTBOX_JUCEHEADER__
  41300. /**
  41301. One of these is used by a TableListBox as the data model for the table's contents.
  41302. The virtual methods that you override in this class take care of drawing the
  41303. table cells, and reacting to events.
  41304. @see TableListBox
  41305. */
  41306. class JUCE_API TableListBoxModel
  41307. {
  41308. public:
  41309. TableListBoxModel() {}
  41310. /** Destructor. */
  41311. virtual ~TableListBoxModel() {}
  41312. /** This must return the number of rows currently in the table.
  41313. If the number of rows changes, you must call TableListBox::updateContent() to
  41314. cause it to refresh the list.
  41315. */
  41316. virtual int getNumRows() = 0;
  41317. /** This must draw the background behind one of the rows in the table.
  41318. The graphics context has its origin at the row's top-left, and your method
  41319. should fill the area specified by the width and height parameters.
  41320. */
  41321. virtual void paintRowBackground (Graphics& g,
  41322. int rowNumber,
  41323. int width, int height,
  41324. bool rowIsSelected) = 0;
  41325. /** This must draw one of the cells.
  41326. The graphics context's origin will already be set to the top-left of the cell,
  41327. whose size is specified by (width, height).
  41328. */
  41329. virtual void paintCell (Graphics& g,
  41330. int rowNumber,
  41331. int columnId,
  41332. int width, int height,
  41333. bool rowIsSelected) = 0;
  41334. /** This is used to create or update a custom component to go in a cell.
  41335. Any cell may contain a custom component, or can just be drawn with the paintCell() method
  41336. and handle mouse clicks with cellClicked().
  41337. This method will be called whenever a custom component might need to be updated - e.g.
  41338. when the table is changed, or TableListBox::updateContent() is called.
  41339. If you don't need a custom component for the specified cell, then return 0.
  41340. If you do want a custom component, and the existingComponentToUpdate is null, then
  41341. this method must create a new component suitable for the cell, and return it.
  41342. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  41343. by this method. In this case, the method must either update it to make sure it's correctly representing
  41344. the given cell (which may be different from the one that the component was created for), or it can
  41345. delete this component and return a new one.
  41346. */
  41347. virtual Component* refreshComponentForCell (int rowNumber, int columnId, bool isRowSelected,
  41348. Component* existingComponentToUpdate);
  41349. /** This callback is made when the user clicks on one of the cells in the table.
  41350. The mouse event's coordinates will be relative to the entire table row.
  41351. @see cellDoubleClicked, backgroundClicked
  41352. */
  41353. virtual void cellClicked (int rowNumber, int columnId, const MouseEvent& e);
  41354. /** This callback is made when the user clicks on one of the cells in the table.
  41355. The mouse event's coordinates will be relative to the entire table row.
  41356. @see cellClicked, backgroundClicked
  41357. */
  41358. virtual void cellDoubleClicked (int rowNumber, int columnId, const MouseEvent& e);
  41359. /** This can be overridden to react to the user double-clicking on a part of the list where
  41360. there are no rows.
  41361. @see cellClicked
  41362. */
  41363. virtual void backgroundClicked();
  41364. /** This callback is made when the table's sort order is changed.
  41365. This could be because the user has clicked a column header, or because the
  41366. TableHeaderComponent::setSortColumnId() method was called.
  41367. If you implement this, your method should re-sort the table using the given
  41368. column as the key.
  41369. */
  41370. virtual void sortOrderChanged (int newSortColumnId, bool isForwards);
  41371. /** Returns the best width for one of the columns.
  41372. If you implement this method, you should measure the width of all the items
  41373. in this column, and return the best size.
  41374. Returning 0 means that the column shouldn't be changed.
  41375. This is used by TableListBox::autoSizeColumn() and TableListBox::autoSizeAllColumns().
  41376. */
  41377. virtual int getColumnAutoSizeWidth (int columnId);
  41378. /** Returns a tooltip for a particular cell in the table.
  41379. */
  41380. virtual const String getCellTooltip (int rowNumber, int columnId);
  41381. /** Override this to be informed when rows are selected or deselected.
  41382. @see ListBox::selectedRowsChanged()
  41383. */
  41384. virtual void selectedRowsChanged (int lastRowSelected);
  41385. /** Override this to be informed when the delete key is pressed.
  41386. @see ListBox::deleteKeyPressed()
  41387. */
  41388. virtual void deleteKeyPressed (int lastRowSelected);
  41389. /** Override this to be informed when the return key is pressed.
  41390. @see ListBox::returnKeyPressed()
  41391. */
  41392. virtual void returnKeyPressed (int lastRowSelected);
  41393. /** Override this to be informed when the list is scrolled.
  41394. This might be caused by the user moving the scrollbar, or by programmatic changes
  41395. to the list position.
  41396. */
  41397. virtual void listWasScrolled();
  41398. /** To allow rows from your table to be dragged-and-dropped, implement this method.
  41399. If this returns a non-null variant then when the user drags a row, the table will try to
  41400. find a DragAndDropContainer in its parent hierarchy, and will use it to trigger a
  41401. drag-and-drop operation, using this string as the source description, and the listbox
  41402. itself as the source component.
  41403. @see getDragSourceCustomData, DragAndDropContainer::startDragging
  41404. */
  41405. virtual const var getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  41406. };
  41407. /**
  41408. A table of cells, using a TableHeaderComponent as its header.
  41409. This component makes it easy to create a table by providing a TableListBoxModel as
  41410. the data source.
  41411. @see TableListBoxModel, TableHeaderComponent
  41412. */
  41413. class JUCE_API TableListBox : public ListBox,
  41414. private ListBoxModel,
  41415. private TableHeaderComponent::Listener
  41416. {
  41417. public:
  41418. /** Creates a TableListBox.
  41419. The model pointer passed-in can be null, in which case you can set it later
  41420. with setModel().
  41421. */
  41422. TableListBox (const String& componentName = String::empty,
  41423. TableListBoxModel* model = 0);
  41424. /** Destructor. */
  41425. ~TableListBox();
  41426. /** Changes the TableListBoxModel that is being used for this table.
  41427. */
  41428. void setModel (TableListBoxModel* newModel);
  41429. /** Returns the model currently in use. */
  41430. TableListBoxModel* getModel() const { return model; }
  41431. /** Returns the header component being used in this table. */
  41432. TableHeaderComponent& getHeader() const { return *header; }
  41433. /** Sets the header component to use for the table.
  41434. The table will take ownership of the component that you pass in, and will delete it
  41435. when it's no longer needed.
  41436. */
  41437. void setHeader (TableHeaderComponent* newHeader);
  41438. /** Changes the height of the table header component.
  41439. @see getHeaderHeight
  41440. */
  41441. void setHeaderHeight (int newHeight);
  41442. /** Returns the height of the table header.
  41443. @see setHeaderHeight
  41444. */
  41445. int getHeaderHeight() const;
  41446. /** Resizes a column to fit its contents.
  41447. This uses TableListBoxModel::getColumnAutoSizeWidth() to find the best width,
  41448. and applies that to the column.
  41449. @see autoSizeAllColumns, TableHeaderComponent::setColumnWidth
  41450. */
  41451. void autoSizeColumn (int columnId);
  41452. /** Calls autoSizeColumn() for all columns in the table. */
  41453. void autoSizeAllColumns();
  41454. /** Enables or disables the auto size options on the popup menu.
  41455. By default, these are enabled.
  41456. */
  41457. void setAutoSizeMenuOptionShown (bool shouldBeShown);
  41458. /** True if the auto-size options should be shown on the menu.
  41459. @see setAutoSizeMenuOptionsShown
  41460. */
  41461. bool isAutoSizeMenuOptionShown() const;
  41462. /** Returns the position of one of the cells in the table.
  41463. If relativeToComponentTopLeft is true, the co-ordinates are relative to
  41464. the table component's top-left. The row number isn't checked to see if it's
  41465. in-range, but the column ID must exist or this will return an empty rectangle.
  41466. If relativeToComponentTopLeft is false, the co-ords are relative to the
  41467. top-left of the table's top-left cell.
  41468. */
  41469. const Rectangle<int> getCellPosition (int columnId, int rowNumber,
  41470. bool relativeToComponentTopLeft) const;
  41471. /** Returns the component that currently represents a given cell.
  41472. If the component for this cell is off-screen or if the position is out-of-range,
  41473. this may return 0.
  41474. @see getCellPosition
  41475. */
  41476. Component* getCellComponent (int columnId, int rowNumber) const;
  41477. /** Scrolls horizontally if necessary to make sure that a particular column is visible.
  41478. @see ListBox::scrollToEnsureRowIsOnscreen
  41479. */
  41480. void scrollToEnsureColumnIsOnscreen (int columnId);
  41481. /** @internal */
  41482. int getNumRows();
  41483. /** @internal */
  41484. void paintListBoxItem (int, Graphics&, int, int, bool);
  41485. /** @internal */
  41486. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  41487. /** @internal */
  41488. void selectedRowsChanged (int lastRowSelected);
  41489. /** @internal */
  41490. void deleteKeyPressed (int currentSelectedRow);
  41491. /** @internal */
  41492. void returnKeyPressed (int currentSelectedRow);
  41493. /** @internal */
  41494. void backgroundClicked();
  41495. /** @internal */
  41496. void listWasScrolled();
  41497. /** @internal */
  41498. void tableColumnsChanged (TableHeaderComponent*);
  41499. /** @internal */
  41500. void tableColumnsResized (TableHeaderComponent*);
  41501. /** @internal */
  41502. void tableSortOrderChanged (TableHeaderComponent*);
  41503. /** @internal */
  41504. void tableColumnDraggingChanged (TableHeaderComponent*, int);
  41505. /** @internal */
  41506. void resized();
  41507. private:
  41508. TableHeaderComponent* header;
  41509. TableListBoxModel* model;
  41510. int columnIdNowBeingDragged;
  41511. bool autoSizeOptionsShown;
  41512. void updateColumnComponents() const;
  41513. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListBox);
  41514. };
  41515. #endif // __JUCE_TABLELISTBOX_JUCEHEADER__
  41516. /*** End of inlined file: juce_TableListBox.h ***/
  41517. #endif
  41518. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  41519. #endif
  41520. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  41521. #endif
  41522. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  41523. #endif
  41524. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  41525. /*** Start of inlined file: juce_ToolbarItemFactory.h ***/
  41526. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  41527. #define __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  41528. /**
  41529. A factory object which can create ToolbarItemComponent objects.
  41530. A subclass of ToolbarItemFactory publishes a set of types of toolbar item
  41531. that it can create.
  41532. Each type of item is identified by a unique ID, and multiple instances of an
  41533. item type can exist at once (even on the same toolbar, e.g. spacers or separator
  41534. bars).
  41535. @see Toolbar, ToolbarItemComponent, ToolbarButton
  41536. */
  41537. class JUCE_API ToolbarItemFactory
  41538. {
  41539. public:
  41540. ToolbarItemFactory();
  41541. /** Destructor. */
  41542. virtual ~ToolbarItemFactory();
  41543. /** A set of reserved item ID values, used for the built-in item types.
  41544. */
  41545. enum SpecialItemIds
  41546. {
  41547. separatorBarId = -1, /**< The item ID for a vertical (or horizontal) separator bar that
  41548. can be placed between sets of items to break them into groups. */
  41549. spacerId = -2, /**< The item ID for a fixed-width space that can be placed between
  41550. items.*/
  41551. flexibleSpacerId = -3 /**< The item ID for a gap that pushes outwards against the things on
  41552. either side of it, filling any available space. */
  41553. };
  41554. /** Must return a list of the IDs for all the item types that this factory can create.
  41555. The ids should be added to the array that is passed-in.
  41556. An item ID can be any integer you choose, except for 0, which is considered a null ID,
  41557. and the predefined IDs in the SpecialItemIds enum.
  41558. You should also add the built-in types (separatorBarId, spacerId and flexibleSpacerId)
  41559. to this list if you want your toolbar to be able to contain those items.
  41560. The list returned here is used by the ToolbarItemPalette class to obtain its list
  41561. of available items, and their order on the palette will reflect the order in which
  41562. they appear on this list.
  41563. @see ToolbarItemPalette
  41564. */
  41565. virtual void getAllToolbarItemIds (Array <int>& ids) = 0;
  41566. /** Must return the set of items that should be added to a toolbar as its default set.
  41567. This method is used by Toolbar::addDefaultItems() to determine which items to
  41568. create.
  41569. The items that your method adds to the array that is passed-in will be added to the
  41570. toolbar in the same order. Items can appear in the list more than once.
  41571. */
  41572. virtual void getDefaultItemSet (Array <int>& ids) = 0;
  41573. /** Must create an instance of one of the items that the factory lists in its
  41574. getAllToolbarItemIds() method.
  41575. The itemId parameter can be any of the values listed by your getAllToolbarItemIds()
  41576. method, except for the built-in item types from the SpecialItemIds enum, which
  41577. are created internally by the toolbar code.
  41578. Try not to keep a pointer to the object that is returned, as it will be deleted
  41579. automatically by the toolbar, and remember that multiple instances of the same
  41580. item type are likely to exist at the same time.
  41581. */
  41582. virtual ToolbarItemComponent* createItem (int itemId) = 0;
  41583. };
  41584. #endif // __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  41585. /*** End of inlined file: juce_ToolbarItemFactory.h ***/
  41586. #endif
  41587. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  41588. /*** Start of inlined file: juce_ToolbarItemPalette.h ***/
  41589. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  41590. #define __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  41591. /**
  41592. A component containing a list of toolbar items, which the user can drag onto
  41593. a toolbar to add them.
  41594. You can use this class directly, but it's a lot easier to call Toolbar::showCustomisationDialog(),
  41595. which automatically shows one of these in a dialog box with lots of extra controls.
  41596. @see Toolbar
  41597. */
  41598. class JUCE_API ToolbarItemPalette : public Component,
  41599. public DragAndDropContainer
  41600. {
  41601. public:
  41602. /** Creates a palette of items for a given factory, with the aim of adding them
  41603. to the specified toolbar.
  41604. The ToolbarItemFactory::getAllToolbarItemIds() method is used to create the
  41605. set of items that are shown in this palette.
  41606. The toolbar and factory must not be deleted while this object exists.
  41607. */
  41608. ToolbarItemPalette (ToolbarItemFactory& factory,
  41609. Toolbar* toolbar);
  41610. /** Destructor. */
  41611. ~ToolbarItemPalette();
  41612. /** @internal */
  41613. void resized();
  41614. private:
  41615. ToolbarItemFactory& factory;
  41616. Toolbar* toolbar;
  41617. Viewport viewport;
  41618. OwnedArray <ToolbarItemComponent> items;
  41619. friend class Toolbar;
  41620. void replaceComponent (ToolbarItemComponent* comp);
  41621. void addComponent (int itemId, int index);
  41622. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarItemPalette);
  41623. };
  41624. #endif // __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  41625. /*** End of inlined file: juce_ToolbarItemPalette.h ***/
  41626. #endif
  41627. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  41628. /*** Start of inlined file: juce_TreeView.h ***/
  41629. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  41630. #define __JUCE_TREEVIEW_JUCEHEADER__
  41631. /*** Start of inlined file: juce_FileDragAndDropTarget.h ***/
  41632. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  41633. #define __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  41634. /**
  41635. Components derived from this class can have files dropped onto them by an external application.
  41636. @see DragAndDropContainer
  41637. */
  41638. class JUCE_API FileDragAndDropTarget
  41639. {
  41640. public:
  41641. /** Destructor. */
  41642. virtual ~FileDragAndDropTarget() {}
  41643. /** Callback to check whether this target is interested in the set of files being offered.
  41644. Note that this will be called repeatedly when the user is dragging the mouse around over your
  41645. component, so don't do anything time-consuming in here, like opening the files to have a look
  41646. inside them!
  41647. @param files the set of (absolute) pathnames of the files that the user is dragging
  41648. @returns true if this component wants to receive the other callbacks regarging this
  41649. type of object; if it returns false, no other callbacks will be made.
  41650. */
  41651. virtual bool isInterestedInFileDrag (const StringArray& files) = 0;
  41652. /** Callback to indicate that some files are being dragged over this component.
  41653. This gets called when the user moves the mouse into this component while dragging.
  41654. Use this callback as a trigger to make your component repaint itself to give the
  41655. user feedback about whether the files can be dropped here or not.
  41656. @param files the set of (absolute) pathnames of the files that the user is dragging
  41657. @param x the mouse x position, relative to this component
  41658. @param y the mouse y position, relative to this component
  41659. */
  41660. virtual void fileDragEnter (const StringArray& files, int x, int y);
  41661. /** Callback to indicate that the user is dragging some files over this component.
  41662. This gets called when the user moves the mouse over this component while dragging.
  41663. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  41664. this lets you know what happens in-between.
  41665. @param files the set of (absolute) pathnames of the files that the user is dragging
  41666. @param x the mouse x position, relative to this component
  41667. @param y the mouse y position, relative to this component
  41668. */
  41669. virtual void fileDragMove (const StringArray& files, int x, int y);
  41670. /** Callback to indicate that the mouse has moved away from this component.
  41671. This gets called when the user moves the mouse out of this component while dragging
  41672. the files.
  41673. If you've used fileDragEnter() to repaint your component and give feedback, use this
  41674. as a signal to repaint it in its normal state.
  41675. @param files the set of (absolute) pathnames of the files that the user is dragging
  41676. */
  41677. virtual void fileDragExit (const StringArray& files);
  41678. /** Callback to indicate that the user has dropped the files onto this component.
  41679. When the user drops the files, this get called, and you can use the files in whatever
  41680. way is appropriate.
  41681. Note that after this is called, the fileDragExit method may not be called, so you should
  41682. clean up in here if there's anything you need to do when the drag finishes.
  41683. @param files the set of (absolute) pathnames of the files that the user is dragging
  41684. @param x the mouse x position, relative to this component
  41685. @param y the mouse y position, relative to this component
  41686. */
  41687. virtual void filesDropped (const StringArray& files, int x, int y) = 0;
  41688. };
  41689. #endif // __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  41690. /*** End of inlined file: juce_FileDragAndDropTarget.h ***/
  41691. class TreeView;
  41692. /**
  41693. An item in a treeview.
  41694. A TreeViewItem can either be a leaf-node in the tree, or it can contain its
  41695. own sub-items.
  41696. To implement an item that contains sub-items, override the itemOpennessChanged()
  41697. method so that when it is opened, it adds the new sub-items to itself using the
  41698. addSubItem method. Depending on the nature of the item it might choose to only
  41699. do this the first time it's opened, or it might want to refresh itself each time.
  41700. It also has the option of deleting its sub-items when it is closed, or leaving them
  41701. in place.
  41702. */
  41703. class JUCE_API TreeViewItem
  41704. {
  41705. public:
  41706. /** Constructor. */
  41707. TreeViewItem();
  41708. /** Destructor. */
  41709. virtual ~TreeViewItem();
  41710. /** Returns the number of sub-items that have been added to this item.
  41711. Note that this doesn't mean much if the node isn't open.
  41712. @see getSubItem, mightContainSubItems, addSubItem
  41713. */
  41714. int getNumSubItems() const noexcept;
  41715. /** Returns one of the item's sub-items.
  41716. Remember that the object returned might get deleted at any time when its parent
  41717. item is closed or refreshed, depending on the nature of the items you're using.
  41718. @see getNumSubItems
  41719. */
  41720. TreeViewItem* getSubItem (int index) const noexcept;
  41721. /** Removes any sub-items. */
  41722. void clearSubItems();
  41723. /** Adds a sub-item.
  41724. @param newItem the object to add to the item's sub-item list. Once added, these can be
  41725. found using getSubItem(). When the items are later removed with
  41726. removeSubItem() (or when this item is deleted), they will be deleted.
  41727. @param insertPosition the index which the new item should have when it's added. If this
  41728. value is less than 0, the item will be added to the end of the list.
  41729. */
  41730. void addSubItem (TreeViewItem* newItem, int insertPosition = -1);
  41731. /** Removes one of the sub-items.
  41732. @param index the item to remove
  41733. @param deleteItem if true, the item that is removed will also be deleted.
  41734. */
  41735. void removeSubItem (int index, bool deleteItem = true);
  41736. /** Returns the TreeView to which this item belongs. */
  41737. TreeView* getOwnerView() const noexcept { return ownerView; }
  41738. /** Returns the item within which this item is contained. */
  41739. TreeViewItem* getParentItem() const noexcept { return parentItem; }
  41740. /** True if this item is currently open in the treeview. */
  41741. bool isOpen() const noexcept;
  41742. /** Opens or closes the item.
  41743. When opened or closed, the item's itemOpennessChanged() method will be called,
  41744. and a subclass should use this callback to create and add any sub-items that
  41745. it needs to.
  41746. @see itemOpennessChanged, mightContainSubItems
  41747. */
  41748. void setOpen (bool shouldBeOpen);
  41749. /** True if this item is currently selected.
  41750. Use this when painting the node, to decide whether to draw it as selected or not.
  41751. */
  41752. bool isSelected() const noexcept;
  41753. /** Selects or deselects the item.
  41754. This will cause a callback to itemSelectionChanged()
  41755. */
  41756. void setSelected (bool shouldBeSelected,
  41757. bool deselectOtherItemsFirst);
  41758. /** Returns the rectangle that this item occupies.
  41759. If relativeToTreeViewTopLeft is true, the co-ordinates are relative to the
  41760. top-left of the TreeView comp, so this will depend on the scroll-position of
  41761. the tree. If false, it is relative to the top-left of the topmost item in the
  41762. tree (so this would be unaffected by scrolling the view).
  41763. */
  41764. const Rectangle<int> getItemPosition (bool relativeToTreeViewTopLeft) const noexcept;
  41765. /** Sends a signal to the treeview to make it refresh itself.
  41766. Call this if your items have changed and you want the tree to update to reflect
  41767. this.
  41768. */
  41769. void treeHasChanged() const noexcept;
  41770. /** Sends a repaint message to redraw just this item.
  41771. Note that you should only call this if you want to repaint a superficial change. If
  41772. you're altering the tree's nodes, you should instead call treeHasChanged().
  41773. */
  41774. void repaintItem() const;
  41775. /** Returns the row number of this item in the tree.
  41776. The row number of an item will change according to which items are open.
  41777. @see TreeView::getNumRowsInTree(), TreeView::getItemOnRow()
  41778. */
  41779. int getRowNumberInTree() const noexcept;
  41780. /** Returns true if all the item's parent nodes are open.
  41781. This is useful to check whether the item might actually be visible or not.
  41782. */
  41783. bool areAllParentsOpen() const noexcept;
  41784. /** Changes whether lines are drawn to connect any sub-items to this item.
  41785. By default, line-drawing is turned on.
  41786. */
  41787. void setLinesDrawnForSubItems (bool shouldDrawLines) noexcept;
  41788. /** Tells the tree whether this item can potentially be opened.
  41789. If your item could contain sub-items, this should return true; if it returns
  41790. false then the tree will not try to open the item. This determines whether or
  41791. not the item will be drawn with a 'plus' button next to it.
  41792. */
  41793. virtual bool mightContainSubItems() = 0;
  41794. /** Returns a string to uniquely identify this item.
  41795. If you're planning on using the TreeView::getOpennessState() method, then
  41796. these strings will be used to identify which nodes are open. The string
  41797. should be unique amongst the item's sibling items, but it's ok for there
  41798. to be duplicates at other levels of the tree.
  41799. If you're not going to store the state, then it's ok not to bother implementing
  41800. this method.
  41801. */
  41802. virtual const String getUniqueName() const;
  41803. /** Called when an item is opened or closed.
  41804. When setOpen() is called and the item has specified that it might
  41805. have sub-items with the mightContainSubItems() method, this method
  41806. is called to let the item create or manage its sub-items.
  41807. So when this is called with isNowOpen set to true (i.e. when the item is being
  41808. opened), a subclass might choose to use clearSubItems() and addSubItem() to
  41809. refresh its sub-item list.
  41810. When this is called with isNowOpen set to false, the subclass might want
  41811. to use clearSubItems() to save on space, or it might choose to leave them,
  41812. depending on the nature of the tree.
  41813. You could also use this callback as a trigger to start a background process
  41814. which asynchronously creates sub-items and adds them, if that's more
  41815. appropriate for the task in hand.
  41816. @see mightContainSubItems
  41817. */
  41818. virtual void itemOpennessChanged (bool isNowOpen);
  41819. /** Must return the width required by this item.
  41820. If your item needs to have a particular width in pixels, return that value; if
  41821. you'd rather have it just fill whatever space is available in the treeview,
  41822. return -1.
  41823. If all your items return -1, no horizontal scrollbar will be shown, but if any
  41824. items have fixed widths and extend beyond the width of the treeview, a
  41825. scrollbar will appear.
  41826. Each item can be a different width, but if they change width, you should call
  41827. treeHasChanged() to update the tree.
  41828. */
  41829. virtual int getItemWidth() const { return -1; }
  41830. /** Must return the height required by this item.
  41831. This is the height in pixels that the item will take up. Items in the tree
  41832. can be different heights, but if they change height, you should call
  41833. treeHasChanged() to update the tree.
  41834. */
  41835. virtual int getItemHeight() const { return 20; }
  41836. /** You can override this method to return false if you don't want to allow the
  41837. user to select this item.
  41838. */
  41839. virtual bool canBeSelected() const { return true; }
  41840. /** Creates a component that will be used to represent this item.
  41841. You don't have to implement this method - if it returns 0 then no component
  41842. will be used for the item, and you can just draw it using the paintItem()
  41843. callback. But if you do return a component, it will be positioned in the
  41844. treeview so that it can be used to represent this item.
  41845. The component returned will be managed by the treeview, so always return
  41846. a new component, and don't keep a reference to it, as the treeview will
  41847. delete it later when it goes off the screen or is no longer needed. Also
  41848. bear in mind that if the component keeps a reference to the item that
  41849. created it, that item could be deleted before the component. Its position
  41850. and size will be completely managed by the tree, so don't attempt to move it
  41851. around.
  41852. Something you may want to do with your component is to give it a pointer to
  41853. the TreeView that created it. This is perfectly safe, and there's no danger
  41854. of it becoming a dangling pointer because the TreeView will always delete
  41855. the component before it is itself deleted.
  41856. As long as you stick to these rules you can return whatever kind of
  41857. component you like. It's most useful if you're doing things like drag-and-drop
  41858. of items, or want to use a Label component to edit item names, etc.
  41859. */
  41860. virtual Component* createItemComponent() { return nullptr; }
  41861. /** Draws the item's contents.
  41862. You can choose to either implement this method and draw each item, or you
  41863. can use createItemComponent() to create a component that will represent the
  41864. item.
  41865. If all you need in your tree is to be able to draw the items and detect when
  41866. the user selects or double-clicks one of them, it's probably enough to
  41867. use paintItem(), itemClicked() and itemDoubleClicked(). If you need more
  41868. complicated interactions, you may need to use createItemComponent() instead.
  41869. @param g the graphics context to draw into
  41870. @param width the width of the area available for drawing
  41871. @param height the height of the area available for drawing
  41872. */
  41873. virtual void paintItem (Graphics& g, int width, int height);
  41874. /** Draws the item's open/close button.
  41875. If you don't implement this method, the default behaviour is to
  41876. call LookAndFeel::drawTreeviewPlusMinusBox(), but you can override
  41877. it for custom effects.
  41878. */
  41879. virtual void paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver);
  41880. /** Called when the user clicks on this item.
  41881. If you're using createItemComponent() to create a custom component for the
  41882. item, the mouse-clicks might not make it through to the treeview, but this
  41883. is how you find out about clicks when just drawing each item individually.
  41884. The associated mouse-event details are passed in, so you can find out about
  41885. which button, where it was, etc.
  41886. @see itemDoubleClicked
  41887. */
  41888. virtual void itemClicked (const MouseEvent& e);
  41889. /** Called when the user double-clicks on this item.
  41890. If you're using createItemComponent() to create a custom component for the
  41891. item, the mouse-clicks might not make it through to the treeview, but this
  41892. is how you find out about clicks when just drawing each item individually.
  41893. The associated mouse-event details are passed in, so you can find out about
  41894. which button, where it was, etc.
  41895. If not overridden, the base class method here will open or close the item as
  41896. if the 'plus' button had been clicked.
  41897. @see itemClicked
  41898. */
  41899. virtual void itemDoubleClicked (const MouseEvent& e);
  41900. /** Called when the item is selected or deselected.
  41901. Use this if you want to do something special when the item's selectedness
  41902. changes. By default it'll get repainted when this happens.
  41903. */
  41904. virtual void itemSelectionChanged (bool isNowSelected);
  41905. /** The item can return a tool tip string here if it wants to.
  41906. @see TooltipClient
  41907. */
  41908. virtual const String getTooltip();
  41909. /** To allow items from your treeview to be dragged-and-dropped, implement this method.
  41910. If this returns a non-null variant then when the user drags an item, the treeview will
  41911. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  41912. a drag-and-drop operation, using this string as the source description, with the treeview
  41913. itself as the source component.
  41914. If you need more complex drag-and-drop behaviour, you can use custom components for
  41915. the items, and use those to trigger the drag.
  41916. To accept drag-and-drop in your tree, see isInterestedInDragSource(),
  41917. isInterestedInFileDrag(), etc.
  41918. @see DragAndDropContainer::startDragging
  41919. */
  41920. virtual const var getDragSourceDescription();
  41921. /** If you want your item to be able to have files drag-and-dropped onto it, implement this
  41922. method and return true.
  41923. If you return true and allow some files to be dropped, you'll also need to implement the
  41924. filesDropped() method to do something with them.
  41925. Note that this will be called often, so make your implementation very quick! There's
  41926. certainly no time to try opening the files and having a think about what's inside them!
  41927. For responding to internal drag-and-drop of other types of object, see isInterestedInDragSource().
  41928. @see FileDragAndDropTarget::isInterestedInFileDrag, isInterestedInDragSource
  41929. */
  41930. virtual bool isInterestedInFileDrag (const StringArray& files);
  41931. /** When files are dropped into this item, this callback is invoked.
  41932. For this to work, you'll need to have also implemented isInterestedInFileDrag().
  41933. The insertIndex value indicates where in the list of sub-items the files were dropped.
  41934. If files are dropped onto an area of the tree where there are no visible items, this
  41935. method is called on the root item of the tree, with an insert index of 0.
  41936. @see FileDragAndDropTarget::filesDropped, isInterestedInFileDrag
  41937. */
  41938. virtual void filesDropped (const StringArray& files, int insertIndex);
  41939. /** If you want your item to act as a DragAndDropTarget, implement this method and return true.
  41940. If you implement this method, you'll also need to implement itemDropped() in order to handle
  41941. the items when they are dropped.
  41942. To respond to drag-and-drop of files from external applications, see isInterestedInFileDrag().
  41943. @see DragAndDropTarget::isInterestedInDragSource, itemDropped
  41944. */
  41945. virtual bool isInterestedInDragSource (const DragAndDropTarget::SourceDetails& dragSourceDetails);
  41946. /** When a things are dropped into this item, this callback is invoked.
  41947. For this to work, you need to have also implemented isInterestedInDragSource().
  41948. The insertIndex value indicates where in the list of sub-items the new items should be placed.
  41949. If files are dropped onto an area of the tree where there are no visible items, this
  41950. method is called on the root item of the tree, with an insert index of 0.
  41951. @see isInterestedInDragSource, DragAndDropTarget::itemDropped
  41952. */
  41953. virtual void itemDropped (const DragAndDropTarget::SourceDetails& dragSourceDetails, int insertIndex);
  41954. /** Sets a flag to indicate that the item wants to be allowed
  41955. to draw all the way across to the left edge of the treeview.
  41956. By default this is false, which means that when the paintItem()
  41957. method is called, its graphics context is clipped to only allow
  41958. drawing within the item's rectangle. If this flag is set to true,
  41959. then the graphics context isn't clipped on its left side, so it
  41960. can draw all the way across to the left margin. Note that the
  41961. context will still have its origin in the same place though, so
  41962. the coordinates of anything to its left will be negative. It's
  41963. mostly useful if you want to draw a wider bar behind the
  41964. highlighted item.
  41965. */
  41966. void setDrawsInLeftMargin (bool canDrawInLeftMargin) noexcept;
  41967. /** Saves the current state of open/closed nodes so it can be restored later.
  41968. This takes a snapshot of which sub-nodes have been explicitly opened or closed,
  41969. and records it as XML. To identify node objects it uses the
  41970. TreeViewItem::getUniqueName() method to create named paths. This
  41971. means that the same state of open/closed nodes can be restored to a
  41972. completely different instance of the tree, as long as it contains nodes
  41973. whose unique names are the same.
  41974. You'd normally want to use TreeView::getOpennessState() rather than call it
  41975. for a specific item, but this can be handy if you need to briefly save the state
  41976. for a section of the tree.
  41977. The caller is responsible for deleting the object that is returned.
  41978. @see TreeView::getOpennessState, restoreOpennessState
  41979. */
  41980. XmlElement* getOpennessState() const noexcept;
  41981. /** Restores the openness of this item and all its sub-items from a saved state.
  41982. See TreeView::restoreOpennessState for more details.
  41983. You'd normally want to use TreeView::restoreOpennessState() rather than call it
  41984. for a specific item, but this can be handy if you need to briefly save the state
  41985. for a section of the tree.
  41986. @see TreeView::restoreOpennessState, getOpennessState
  41987. */
  41988. void restoreOpennessState (const XmlElement& xml) noexcept;
  41989. /** Returns the index of this item in its parent's sub-items. */
  41990. int getIndexInParent() const noexcept;
  41991. /** Returns true if this item is the last of its parent's sub-itens. */
  41992. bool isLastOfSiblings() const noexcept;
  41993. /** Creates a string that can be used to uniquely retrieve this item in the tree.
  41994. The string that is returned can be passed to TreeView::findItemFromIdentifierString().
  41995. The string takes the form of a path, constructed from the getUniqueName() of this
  41996. item and all its parents, so these must all be correctly implemented for it to work.
  41997. @see TreeView::findItemFromIdentifierString, getUniqueName
  41998. */
  41999. String getItemIdentifierString() const;
  42000. /**
  42001. This handy class takes a copy of a TreeViewItem's openness when you create it,
  42002. and restores that openness state when its destructor is called.
  42003. This can very handy when you're refreshing sub-items - e.g.
  42004. @code
  42005. void MyTreeViewItem::updateChildItems()
  42006. {
  42007. OpennessRestorer openness (*this); // saves the openness state here..
  42008. clearSubItems();
  42009. // add a bunch of sub-items here which may or may not be the same as the ones that
  42010. // were previously there
  42011. addSubItem (...
  42012. // ..and at this point, the old openness is restored, so any items that haven't
  42013. // changed will have their old openness retained.
  42014. }
  42015. @endcode
  42016. */
  42017. class OpennessRestorer
  42018. {
  42019. public:
  42020. OpennessRestorer (TreeViewItem& treeViewItem);
  42021. ~OpennessRestorer();
  42022. private:
  42023. TreeViewItem& treeViewItem;
  42024. ScopedPointer <XmlElement> oldOpenness;
  42025. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpennessRestorer);
  42026. };
  42027. private:
  42028. TreeView* ownerView;
  42029. TreeViewItem* parentItem;
  42030. OwnedArray <TreeViewItem> subItems;
  42031. int y, itemHeight, totalHeight, itemWidth, totalWidth;
  42032. int uid;
  42033. bool selected : 1;
  42034. bool redrawNeeded : 1;
  42035. bool drawLinesInside : 1;
  42036. bool drawsInLeftMargin : 1;
  42037. unsigned int openness : 2;
  42038. friend class TreeView;
  42039. friend class TreeViewContentComponent;
  42040. void updatePositions (int newY);
  42041. int getIndentX() const noexcept;
  42042. void setOwnerView (TreeView*) noexcept;
  42043. void paintRecursively (Graphics&, int width);
  42044. TreeViewItem* getTopLevelItem() noexcept;
  42045. TreeViewItem* findItemRecursively (int y) noexcept;
  42046. TreeViewItem* getDeepestOpenParentItem() noexcept;
  42047. int getNumRows() const noexcept;
  42048. TreeViewItem* getItemOnRow (int index) noexcept;
  42049. void deselectAllRecursively();
  42050. int countSelectedItemsRecursively (int depth) const noexcept;
  42051. TreeViewItem* getSelectedItemWithIndex (int index) noexcept;
  42052. TreeViewItem* getNextVisibleItem (bool recurse) const noexcept;
  42053. TreeViewItem* findItemFromIdentifierString (const String&);
  42054. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  42055. // The parameters for these methods have changed - please update your code!
  42056. virtual void isInterestedInDragSource (const String&, Component*) {}
  42057. virtual int itemDropped (const String&, Component*, int) { return 0; }
  42058. #endif
  42059. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewItem);
  42060. };
  42061. /**
  42062. A tree-view component.
  42063. Use one of these to hold and display a structure of TreeViewItem objects.
  42064. */
  42065. class JUCE_API TreeView : public Component,
  42066. public SettableTooltipClient,
  42067. public FileDragAndDropTarget,
  42068. public DragAndDropTarget,
  42069. private AsyncUpdater
  42070. {
  42071. public:
  42072. /** Creates an empty treeview.
  42073. Once you've got a treeview component, you'll need to give it something to
  42074. display, using the setRootItem() method.
  42075. */
  42076. TreeView (const String& componentName = String::empty);
  42077. /** Destructor. */
  42078. ~TreeView();
  42079. /** Sets the item that is displayed in the treeview.
  42080. A tree has a single root item which contains as many sub-items as it needs. If
  42081. you want the tree to contain a number of root items, you should still use a single
  42082. root item above these, but hide it using setRootItemVisible().
  42083. You can pass in 0 to this method to clear the tree and remove its current root item.
  42084. The object passed in will not be deleted by the treeview, it's up to the caller
  42085. to delete it when no longer needed. BUT make absolutely sure that you don't delete
  42086. this item until you've removed it from the tree, either by calling setRootItem (nullptr),
  42087. or by deleting the tree first. You can also use deleteRootItem() as a quick way
  42088. to delete it.
  42089. */
  42090. void setRootItem (TreeViewItem* newRootItem);
  42091. /** Returns the tree's root item.
  42092. This will be the last object passed to setRootItem(), or 0 if none has been set.
  42093. */
  42094. TreeViewItem* getRootItem() const noexcept { return rootItem; }
  42095. /** This will remove and delete the current root item.
  42096. It's a convenient way of deleting the item and calling setRootItem (nullptr).
  42097. */
  42098. void deleteRootItem();
  42099. /** Changes whether the tree's root item is shown or not.
  42100. If the root item is hidden, only its sub-items will be shown in the treeview - this
  42101. lets you make the tree look as if it's got many root items. If it's hidden, this call
  42102. will also make sure the root item is open (otherwise the treeview would look empty).
  42103. */
  42104. void setRootItemVisible (bool shouldBeVisible);
  42105. /** Returns true if the root item is visible.
  42106. @see setRootItemVisible
  42107. */
  42108. bool isRootItemVisible() const noexcept { return rootItemVisible; }
  42109. /** Sets whether items are open or closed by default.
  42110. Normally, items are closed until the user opens them, but you can use this
  42111. to make them default to being open until explicitly closed.
  42112. @see areItemsOpenByDefault
  42113. */
  42114. void setDefaultOpenness (bool isOpenByDefault);
  42115. /** Returns true if the tree's items default to being open.
  42116. @see setDefaultOpenness
  42117. */
  42118. bool areItemsOpenByDefault() const noexcept { return defaultOpenness; }
  42119. /** This sets a flag to indicate that the tree can be used for multi-selection.
  42120. You can always select multiple items internally by calling the
  42121. TreeViewItem::setSelected() method, but this flag indicates whether the user
  42122. is allowed to multi-select by clicking on the tree.
  42123. By default it is disabled.
  42124. @see isMultiSelectEnabled
  42125. */
  42126. void setMultiSelectEnabled (bool canMultiSelect);
  42127. /** Returns whether multi-select has been enabled for the tree.
  42128. @see setMultiSelectEnabled
  42129. */
  42130. bool isMultiSelectEnabled() const noexcept { return multiSelectEnabled; }
  42131. /** Sets a flag to indicate whether to hide the open/close buttons.
  42132. @see areOpenCloseButtonsVisible
  42133. */
  42134. void setOpenCloseButtonsVisible (bool shouldBeVisible);
  42135. /** Returns whether open/close buttons are shown.
  42136. @see setOpenCloseButtonsVisible
  42137. */
  42138. bool areOpenCloseButtonsVisible() const noexcept { return openCloseButtonsVisible; }
  42139. /** Deselects any items that are currently selected. */
  42140. void clearSelectedItems();
  42141. /** Returns the number of items that are currently selected.
  42142. If maximumDepthToSearchTo is >= 0, it lets you specify a maximum depth to which the
  42143. tree will be recursed.
  42144. @see getSelectedItem, clearSelectedItems
  42145. */
  42146. int getNumSelectedItems (int maximumDepthToSearchTo = -1) const noexcept;
  42147. /** Returns one of the selected items in the tree.
  42148. @param index the index, 0 to (getNumSelectedItems() - 1)
  42149. */
  42150. TreeViewItem* getSelectedItem (int index) const noexcept;
  42151. /** Returns the number of rows the tree is using.
  42152. This will depend on which items are open.
  42153. @see TreeViewItem::getRowNumberInTree()
  42154. */
  42155. int getNumRowsInTree() const;
  42156. /** Returns the item on a particular row of the tree.
  42157. If the index is out of range, this will return 0.
  42158. @see getNumRowsInTree, TreeViewItem::getRowNumberInTree()
  42159. */
  42160. TreeViewItem* getItemOnRow (int index) const;
  42161. /** Returns the item that contains a given y position.
  42162. The y is relative to the top of the TreeView component.
  42163. */
  42164. TreeViewItem* getItemAt (int yPosition) const noexcept;
  42165. /** Tries to scroll the tree so that this item is on-screen somewhere. */
  42166. void scrollToKeepItemVisible (TreeViewItem* item);
  42167. /** Returns the treeview's Viewport object. */
  42168. Viewport* getViewport() const noexcept;
  42169. /** Returns the number of pixels by which each nested level of the tree is indented.
  42170. @see setIndentSize
  42171. */
  42172. int getIndentSize() const noexcept { return indentSize; }
  42173. /** Changes the distance by which each nested level of the tree is indented.
  42174. @see getIndentSize
  42175. */
  42176. void setIndentSize (int newIndentSize);
  42177. /** Searches the tree for an item with the specified identifier.
  42178. The identifer string must have been created by calling TreeViewItem::getItemIdentifierString().
  42179. If no such item exists, this will return false. If the item is found, all of its items
  42180. will be automatically opened.
  42181. */
  42182. TreeViewItem* findItemFromIdentifierString (const String& identifierString) const;
  42183. /** Saves the current state of open/closed nodes so it can be restored later.
  42184. This takes a snapshot of which nodes have been explicitly opened or closed,
  42185. and records it as XML. To identify node objects it uses the
  42186. TreeViewItem::getUniqueName() method to create named paths. This
  42187. means that the same state of open/closed nodes can be restored to a
  42188. completely different instance of the tree, as long as it contains nodes
  42189. whose unique names are the same.
  42190. The caller is responsible for deleting the object that is returned.
  42191. @param alsoIncludeScrollPosition if this is true, the state will also
  42192. include information about where the
  42193. tree has been scrolled to vertically,
  42194. so this can also be restored
  42195. @see restoreOpennessState
  42196. */
  42197. XmlElement* getOpennessState (bool alsoIncludeScrollPosition) const;
  42198. /** Restores a previously saved arrangement of open/closed nodes.
  42199. This will try to restore a snapshot of the tree's state that was created by
  42200. the getOpennessState() method. If any of the nodes named in the original
  42201. XML aren't present in this tree, they will be ignored.
  42202. If restoreStoredSelection is true, it will also try to re-select any items that
  42203. were selected in the stored state.
  42204. @see getOpennessState
  42205. */
  42206. void restoreOpennessState (const XmlElement& newState,
  42207. bool restoreStoredSelection);
  42208. /** A set of colour IDs to use to change the colour of various aspects of the treeview.
  42209. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  42210. methods.
  42211. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  42212. */
  42213. enum ColourIds
  42214. {
  42215. backgroundColourId = 0x1000500, /**< A background colour to fill the component with. */
  42216. linesColourId = 0x1000501, /**< The colour to draw the lines with.*/
  42217. dragAndDropIndicatorColourId = 0x1000502 /**< The colour to use for the drag-and-drop target position indicator. */
  42218. };
  42219. /** @internal */
  42220. void paint (Graphics& g);
  42221. /** @internal */
  42222. void resized();
  42223. /** @internal */
  42224. bool keyPressed (const KeyPress& key);
  42225. /** @internal */
  42226. void colourChanged();
  42227. /** @internal */
  42228. void enablementChanged();
  42229. /** @internal */
  42230. bool isInterestedInFileDrag (const StringArray& files);
  42231. /** @internal */
  42232. void fileDragEnter (const StringArray& files, int x, int y);
  42233. /** @internal */
  42234. void fileDragMove (const StringArray& files, int x, int y);
  42235. /** @internal */
  42236. void fileDragExit (const StringArray& files);
  42237. /** @internal */
  42238. void filesDropped (const StringArray& files, int x, int y);
  42239. /** @internal */
  42240. bool isInterestedInDragSource (const SourceDetails&);
  42241. /** @internal */
  42242. void itemDragEnter (const SourceDetails&);
  42243. /** @internal */
  42244. void itemDragMove (const SourceDetails&);
  42245. /** @internal */
  42246. void itemDragExit (const SourceDetails&);
  42247. /** @internal */
  42248. void itemDropped (const SourceDetails&);
  42249. private:
  42250. friend class TreeViewItem;
  42251. friend class TreeViewContentComponent;
  42252. class TreeViewport;
  42253. class InsertPointHighlight;
  42254. class TargetGroupHighlight;
  42255. friend class ScopedPointer<TreeViewport>;
  42256. friend class ScopedPointer<InsertPointHighlight>;
  42257. friend class ScopedPointer<TargetGroupHighlight>;
  42258. ScopedPointer<TreeViewport> viewport;
  42259. CriticalSection nodeAlterationLock;
  42260. TreeViewItem* rootItem;
  42261. ScopedPointer<InsertPointHighlight> dragInsertPointHighlight;
  42262. ScopedPointer<TargetGroupHighlight> dragTargetGroupHighlight;
  42263. int indentSize;
  42264. bool defaultOpenness : 1;
  42265. bool needsRecalculating : 1;
  42266. bool rootItemVisible : 1;
  42267. bool multiSelectEnabled : 1;
  42268. bool openCloseButtonsVisible : 1;
  42269. void itemsChanged() noexcept;
  42270. void handleAsyncUpdate();
  42271. void moveSelectedRow (int delta);
  42272. void updateButtonUnderMouse (const MouseEvent& e);
  42273. void showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) noexcept;
  42274. void hideDragHighlight() noexcept;
  42275. void handleDrag (const StringArray& files, const SourceDetails&);
  42276. void handleDrop (const StringArray& files, const SourceDetails&);
  42277. TreeViewItem* getInsertPosition (int& x, int& y, int& insertIndex,
  42278. const StringArray& files, const SourceDetails&) const noexcept;
  42279. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeView);
  42280. };
  42281. #endif // __JUCE_TREEVIEW_JUCEHEADER__
  42282. /*** End of inlined file: juce_TreeView.h ***/
  42283. #endif
  42284. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  42285. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  42286. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  42287. #define __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  42288. /*** Start of inlined file: juce_DirectoryContentsList.h ***/
  42289. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  42290. #define __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  42291. /*** Start of inlined file: juce_FileFilter.h ***/
  42292. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  42293. #define __JUCE_FILEFILTER_JUCEHEADER__
  42294. /**
  42295. Interface for deciding which files are suitable for something.
  42296. For example, this is used by DirectoryContentsList to select which files
  42297. go into the list.
  42298. @see WildcardFileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  42299. */
  42300. class JUCE_API FileFilter
  42301. {
  42302. public:
  42303. /** Creates a filter with the given description.
  42304. The description can be returned later with the getDescription() method.
  42305. */
  42306. FileFilter (const String& filterDescription);
  42307. /** Destructor. */
  42308. virtual ~FileFilter();
  42309. /** Returns the description that the filter was created with. */
  42310. const String& getDescription() const noexcept;
  42311. /** Should return true if this file is suitable for inclusion in whatever context
  42312. the object is being used.
  42313. */
  42314. virtual bool isFileSuitable (const File& file) const = 0;
  42315. /** Should return true if this directory is suitable for inclusion in whatever context
  42316. the object is being used.
  42317. */
  42318. virtual bool isDirectorySuitable (const File& file) const = 0;
  42319. protected:
  42320. String description;
  42321. };
  42322. #endif // __JUCE_FILEFILTER_JUCEHEADER__
  42323. /*** End of inlined file: juce_FileFilter.h ***/
  42324. /**
  42325. A class to asynchronously scan for details about the files in a directory.
  42326. This keeps a list of files and some information about them, using a background
  42327. thread to scan for more files. As files are found, it broadcasts change messages
  42328. to tell any listeners.
  42329. @see FileListComponent, FileBrowserComponent
  42330. */
  42331. class JUCE_API DirectoryContentsList : public ChangeBroadcaster,
  42332. public TimeSliceClient
  42333. {
  42334. public:
  42335. /** Creates a directory list.
  42336. To set the directory it should point to, use setDirectory(), which will
  42337. also start it scanning for files on the background thread.
  42338. When the background thread finds and adds new files to this list, the
  42339. ChangeBroadcaster class will send a change message, so you can register
  42340. listeners and update them when the list changes.
  42341. @param fileFilter an optional filter to select which files are
  42342. included in the list. If this is 0, then all files
  42343. and directories are included. Make sure that the
  42344. filter doesn't get deleted during the lifetime of this
  42345. object
  42346. @param threadToUse a thread object that this list can use
  42347. to scan for files as a background task. Make sure
  42348. that the thread you give it has been started, or you
  42349. won't get any files!
  42350. */
  42351. DirectoryContentsList (const FileFilter* fileFilter,
  42352. TimeSliceThread& threadToUse);
  42353. /** Destructor. */
  42354. ~DirectoryContentsList();
  42355. /** Sets the directory to look in for files.
  42356. If the directory that's passed in is different to the current one, this will
  42357. also start the background thread scanning it for files.
  42358. */
  42359. void setDirectory (const File& directory,
  42360. bool includeDirectories,
  42361. bool includeFiles);
  42362. /** Returns the directory that's currently being used. */
  42363. const File& getDirectory() const;
  42364. /** Clears the list, and stops the thread scanning for files. */
  42365. void clear();
  42366. /** Clears the list and restarts scanning the directory for files. */
  42367. void refresh();
  42368. /** True if the background thread hasn't yet finished scanning for files. */
  42369. bool isStillLoading() const;
  42370. /** Tells the list whether or not to ignore hidden files.
  42371. By default these are ignored.
  42372. */
  42373. void setIgnoresHiddenFiles (bool shouldIgnoreHiddenFiles);
  42374. /** Returns true if hidden files are ignored.
  42375. @see setIgnoresHiddenFiles
  42376. */
  42377. bool ignoresHiddenFiles() const;
  42378. /** Contains cached information about one of the files in a DirectoryContentsList.
  42379. */
  42380. struct FileInfo
  42381. {
  42382. /** The filename.
  42383. This isn't a full pathname, it's just the last part of the path, same as you'd
  42384. get from File::getFileName().
  42385. To get the full pathname, use DirectoryContentsList::getDirectory().getChildFile (filename).
  42386. */
  42387. String filename;
  42388. /** File size in bytes. */
  42389. int64 fileSize;
  42390. /** File modification time.
  42391. As supplied by File::getLastModificationTime().
  42392. */
  42393. Time modificationTime;
  42394. /** File creation time.
  42395. As supplied by File::getCreationTime().
  42396. */
  42397. Time creationTime;
  42398. /** True if the file is a directory. */
  42399. bool isDirectory;
  42400. /** True if the file is read-only. */
  42401. bool isReadOnly;
  42402. };
  42403. /** Returns the number of files currently available in the list.
  42404. The info about one of these files can be retrieved with getFileInfo() or
  42405. getFile().
  42406. Obviously as the background thread runs and scans the directory for files, this
  42407. number will change.
  42408. @see getFileInfo, getFile
  42409. */
  42410. int getNumFiles() const;
  42411. /** Returns the cached information about one of the files in the list.
  42412. If the index is in-range, this will return true and will copy the file's details
  42413. to the structure that is passed-in.
  42414. If it returns false, then the index wasn't in range, and the structure won't
  42415. be affected.
  42416. @see getNumFiles, getFile
  42417. */
  42418. bool getFileInfo (int index, FileInfo& resultInfo) const;
  42419. /** Returns one of the files in the list.
  42420. @param index should be less than getNumFiles(). If this is out-of-range, the
  42421. return value will be File::nonexistent
  42422. @see getNumFiles, getFileInfo
  42423. */
  42424. File getFile (int index) const;
  42425. /** Returns the file filter being used.
  42426. The filter is specified in the constructor.
  42427. */
  42428. const FileFilter* getFilter() const { return fileFilter; }
  42429. /** @internal */
  42430. int useTimeSlice();
  42431. /** @internal */
  42432. TimeSliceThread& getTimeSliceThread() { return thread; }
  42433. /** @internal */
  42434. static int compareElements (const DirectoryContentsList::FileInfo* first,
  42435. const DirectoryContentsList::FileInfo* second);
  42436. private:
  42437. File root;
  42438. const FileFilter* fileFilter;
  42439. TimeSliceThread& thread;
  42440. int fileTypeFlags;
  42441. CriticalSection fileListLock;
  42442. OwnedArray <FileInfo> files;
  42443. ScopedPointer <DirectoryIterator> fileFindHandle;
  42444. bool volatile shouldStop;
  42445. void changed();
  42446. bool checkNextFile (bool& hasChanged);
  42447. bool addFile (const File& file, bool isDir,
  42448. const int64 fileSize, const Time& modTime,
  42449. const Time& creationTime, bool isReadOnly);
  42450. void setTypeFlags (int newFlags);
  42451. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectoryContentsList);
  42452. };
  42453. #endif // __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  42454. /*** End of inlined file: juce_DirectoryContentsList.h ***/
  42455. /*** Start of inlined file: juce_FileBrowserListener.h ***/
  42456. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  42457. #define __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  42458. /**
  42459. A listener for user selection events in a file browser.
  42460. This is used by a FileBrowserComponent or FileListComponent.
  42461. */
  42462. class JUCE_API FileBrowserListener
  42463. {
  42464. public:
  42465. /** Destructor. */
  42466. virtual ~FileBrowserListener();
  42467. /** Callback when the user selects a different file in the browser. */
  42468. virtual void selectionChanged() = 0;
  42469. /** Callback when the user clicks on a file in the browser. */
  42470. virtual void fileClicked (const File& file, const MouseEvent& e) = 0;
  42471. /** Callback when the user double-clicks on a file in the browser. */
  42472. virtual void fileDoubleClicked (const File& file) = 0;
  42473. };
  42474. #endif // __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  42475. /*** End of inlined file: juce_FileBrowserListener.h ***/
  42476. /**
  42477. A base class for components that display a list of the files in a directory.
  42478. @see DirectoryContentsList
  42479. */
  42480. class JUCE_API DirectoryContentsDisplayComponent
  42481. {
  42482. public:
  42483. /** Creates a DirectoryContentsDisplayComponent for a given list of files. */
  42484. DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow);
  42485. /** Destructor. */
  42486. virtual ~DirectoryContentsDisplayComponent();
  42487. /** Returns the number of files the user has got selected.
  42488. @see getSelectedFile
  42489. */
  42490. virtual int getNumSelectedFiles() const = 0;
  42491. /** Returns one of the files that the user has currently selected.
  42492. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  42493. @see getNumSelectedFiles
  42494. */
  42495. virtual const File getSelectedFile (int index) const = 0;
  42496. /** Deselects any selected files. */
  42497. virtual void deselectAllFiles() = 0;
  42498. /** Scrolls this view to the top. */
  42499. virtual void scrollToTop() = 0;
  42500. /** Adds a listener to be told when files are selected or clicked.
  42501. @see removeListener
  42502. */
  42503. void addListener (FileBrowserListener* listener);
  42504. /** Removes a listener.
  42505. @see addListener
  42506. */
  42507. void removeListener (FileBrowserListener* listener);
  42508. /** A set of colour IDs to use to change the colour of various aspects of the list.
  42509. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  42510. methods.
  42511. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  42512. */
  42513. enum ColourIds
  42514. {
  42515. highlightColourId = 0x1000540, /**< The colour to use to fill a highlighted row of the list. */
  42516. textColourId = 0x1000541, /**< The colour for the text. */
  42517. };
  42518. /** @internal */
  42519. void sendSelectionChangeMessage();
  42520. /** @internal */
  42521. void sendDoubleClickMessage (const File& file);
  42522. /** @internal */
  42523. void sendMouseClickMessage (const File& file, const MouseEvent& e);
  42524. protected:
  42525. DirectoryContentsList& fileList;
  42526. ListenerList <FileBrowserListener> listeners;
  42527. private:
  42528. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectoryContentsDisplayComponent);
  42529. };
  42530. #endif // __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  42531. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  42532. #endif
  42533. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  42534. #endif
  42535. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  42536. /*** Start of inlined file: juce_FileBrowserComponent.h ***/
  42537. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  42538. #define __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  42539. /*** Start of inlined file: juce_FilePreviewComponent.h ***/
  42540. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  42541. #define __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  42542. /**
  42543. Base class for components that live inside a file chooser dialog box and
  42544. show previews of the files that get selected.
  42545. One of these allows special extra information to be displayed for files
  42546. in a dialog box as the user selects them. Each time the current file or
  42547. directory is changed, the selectedFileChanged() method will be called
  42548. to allow it to update itself appropriately.
  42549. @see FileChooser, ImagePreviewComponent
  42550. */
  42551. class JUCE_API FilePreviewComponent : public Component
  42552. {
  42553. public:
  42554. /** Creates a FilePreviewComponent. */
  42555. FilePreviewComponent();
  42556. /** Destructor. */
  42557. ~FilePreviewComponent();
  42558. /** Called to indicate that the user's currently selected file has changed.
  42559. @param newSelectedFile the newly selected file or directory, which may be
  42560. File::nonexistent if none is selected.
  42561. */
  42562. virtual void selectedFileChanged (const File& newSelectedFile) = 0;
  42563. private:
  42564. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FilePreviewComponent);
  42565. };
  42566. #endif // __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  42567. /*** End of inlined file: juce_FilePreviewComponent.h ***/
  42568. /**
  42569. A component for browsing and selecting a file or directory to open or save.
  42570. This contains a FileListComponent and adds various boxes and controls for
  42571. navigating and selecting a file. It can work in different modes so that it can
  42572. be used for loading or saving a file, or for choosing a directory.
  42573. @see FileChooserDialogBox, FileChooser, FileListComponent
  42574. */
  42575. class JUCE_API FileBrowserComponent : public Component,
  42576. public ChangeBroadcaster,
  42577. private FileBrowserListener,
  42578. private TextEditorListener,
  42579. private ButtonListener,
  42580. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  42581. private FileFilter
  42582. {
  42583. public:
  42584. /** Various options for the browser.
  42585. A combination of these is passed into the FileBrowserComponent constructor.
  42586. */
  42587. enum FileChooserFlags
  42588. {
  42589. openMode = 1, /**< specifies that the component should allow the user to
  42590. choose an existing file with the intention of opening it. */
  42591. saveMode = 2, /**< specifies that the component should allow the user to specify
  42592. the name of a file that will be used to save something. */
  42593. canSelectFiles = 4, /**< specifies that the user can select files (can be used in
  42594. conjunction with canSelectDirectories). */
  42595. canSelectDirectories = 8, /**< specifies that the user can select directories (can be used in
  42596. conjuction with canSelectFiles). */
  42597. canSelectMultipleItems = 16, /**< specifies that the user can select multiple items. */
  42598. useTreeView = 32, /**< specifies that a tree-view should be shown instead of a file list. */
  42599. filenameBoxIsReadOnly = 64 /**< specifies that the user can't type directly into the filename box. */
  42600. };
  42601. /** Creates a FileBrowserComponent.
  42602. @param flags A combination of flags from the FileChooserFlags enumeration,
  42603. used to specify the component's behaviour. The flags must contain
  42604. either openMode or saveMode, and canSelectFiles and/or
  42605. canSelectDirectories.
  42606. @param initialFileOrDirectory The file or directory that should be selected when
  42607. the component begins. If this is File::nonexistent,
  42608. a default directory will be chosen.
  42609. @param fileFilter an optional filter to use to determine which files
  42610. are shown. If this is 0 then all files are displayed. Note
  42611. that a pointer is kept internally to this object, so
  42612. make sure that it is not deleted before the browser object
  42613. is deleted.
  42614. @param previewComp an optional preview component that will be used to
  42615. show previews of files that the user selects
  42616. */
  42617. FileBrowserComponent (int flags,
  42618. const File& initialFileOrDirectory,
  42619. const FileFilter* fileFilter,
  42620. FilePreviewComponent* previewComp);
  42621. /** Destructor. */
  42622. ~FileBrowserComponent();
  42623. /** Returns the number of files that the user has got selected.
  42624. If multiple select isn't active, this will only be 0 or 1. To get the complete
  42625. list of files they've chosen, pass an index to getCurrentFile().
  42626. */
  42627. int getNumSelectedFiles() const noexcept;
  42628. /** Returns one of the files that the user has chosen.
  42629. If the box has multi-select enabled, the index lets you specify which of the files
  42630. to get - see getNumSelectedFiles() to find out how many files were chosen.
  42631. @see getHighlightedFile
  42632. */
  42633. File getSelectedFile (int index) const noexcept;
  42634. /** Deselects any files that are currently selected.
  42635. */
  42636. void deselectAllFiles();
  42637. /** Returns true if the currently selected file(s) are usable.
  42638. This can be used to decide whether the user can press "ok" for the
  42639. current file. What it does depends on the mode, so for example in an "open"
  42640. mode, this only returns true if a file has been selected and if it exists.
  42641. In a "save" mode, a non-existent file would also be valid.
  42642. */
  42643. bool currentFileIsValid() const;
  42644. /** This returns the last item in the view that the user has highlighted.
  42645. This may be different from getCurrentFile(), which returns the value
  42646. that is shown in the filename box, and if there are multiple selections,
  42647. this will only return one of them.
  42648. @see getSelectedFile
  42649. */
  42650. File getHighlightedFile() const noexcept;
  42651. /** Returns the directory whose contents are currently being shown in the listbox. */
  42652. const File& getRoot() const;
  42653. /** Changes the directory that's being shown in the listbox. */
  42654. void setRoot (const File& newRootDirectory);
  42655. /** Equivalent to pressing the "up" button to browse the parent directory. */
  42656. void goUp();
  42657. /** Refreshes the directory that's currently being listed. */
  42658. void refresh();
  42659. /** Changes the filter that's being used to sift the files. */
  42660. void setFileFilter (const FileFilter* newFileFilter);
  42661. /** Returns a verb to describe what should happen when the file is accepted.
  42662. E.g. if browsing in "load file" mode, this will be "Open", if in "save file"
  42663. mode, it'll be "Save", etc.
  42664. */
  42665. virtual const String getActionVerb() const;
  42666. /** Returns true if the saveMode flag was set when this component was created.
  42667. */
  42668. bool isSaveMode() const noexcept;
  42669. /** Adds a listener to be told when the user selects and clicks on files.
  42670. @see removeListener
  42671. */
  42672. void addListener (FileBrowserListener* listener);
  42673. /** Removes a listener.
  42674. @see addListener
  42675. */
  42676. void removeListener (FileBrowserListener* listener);
  42677. /** @internal */
  42678. void resized();
  42679. /** @internal */
  42680. void buttonClicked (Button* b);
  42681. /** @internal */
  42682. void comboBoxChanged (ComboBox*);
  42683. /** @internal */
  42684. void textEditorTextChanged (TextEditor& editor);
  42685. /** @internal */
  42686. void textEditorReturnKeyPressed (TextEditor& editor);
  42687. /** @internal */
  42688. void textEditorEscapeKeyPressed (TextEditor& editor);
  42689. /** @internal */
  42690. void textEditorFocusLost (TextEditor& editor);
  42691. /** @internal */
  42692. bool keyPressed (const KeyPress& key);
  42693. /** @internal */
  42694. void selectionChanged();
  42695. /** @internal */
  42696. void fileClicked (const File& f, const MouseEvent& e);
  42697. /** @internal */
  42698. void fileDoubleClicked (const File& f);
  42699. /** @internal */
  42700. bool isFileSuitable (const File& file) const;
  42701. /** @internal */
  42702. bool isDirectorySuitable (const File&) const;
  42703. /** @internal */
  42704. FilePreviewComponent* getPreviewComponent() const noexcept;
  42705. protected:
  42706. /** Returns a list of names and paths for the default places the user might want to look.
  42707. Use an empty string to indicate a section break.
  42708. */
  42709. virtual void getRoots (StringArray& rootNames, StringArray& rootPaths);
  42710. /** Updates the items in the dropdown list of recent paths with the values from getRoots(). */
  42711. void resetRecentPaths();
  42712. private:
  42713. ScopedPointer <DirectoryContentsList> fileList;
  42714. const FileFilter* fileFilter;
  42715. int flags;
  42716. File currentRoot;
  42717. Array<File> chosenFiles;
  42718. ListenerList <FileBrowserListener> listeners;
  42719. ScopedPointer<DirectoryContentsDisplayComponent> fileListComponent;
  42720. FilePreviewComponent* previewComp;
  42721. ComboBox currentPathBox;
  42722. TextEditor filenameBox;
  42723. Label fileLabel;
  42724. ScopedPointer<Button> goUpButton;
  42725. TimeSliceThread thread;
  42726. void sendListenerChangeMessage();
  42727. bool isFileOrDirSuitable (const File& f) const;
  42728. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileBrowserComponent);
  42729. };
  42730. #endif // __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  42731. /*** End of inlined file: juce_FileBrowserComponent.h ***/
  42732. #endif
  42733. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  42734. #endif
  42735. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  42736. /*** Start of inlined file: juce_FileChooser.h ***/
  42737. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  42738. #define __JUCE_FILECHOOSER_JUCEHEADER__
  42739. /**
  42740. Creates a dialog box to choose a file or directory to load or save.
  42741. To use a FileChooser:
  42742. - create one (as a local stack variable is the neatest way)
  42743. - call one of its browseFor.. methods
  42744. - if this returns true, the user has selected a file, so you can retrieve it
  42745. with the getResult() method.
  42746. e.g. @code
  42747. void loadMooseFile()
  42748. {
  42749. FileChooser myChooser ("Please select the moose you want to load...",
  42750. File::getSpecialLocation (File::userHomeDirectory),
  42751. "*.moose");
  42752. if (myChooser.browseForFileToOpen())
  42753. {
  42754. File mooseFile (myChooser.getResult());
  42755. loadMoose (mooseFile);
  42756. }
  42757. }
  42758. @endcode
  42759. */
  42760. class JUCE_API FileChooser
  42761. {
  42762. public:
  42763. /** Creates a FileChooser.
  42764. After creating one of these, use one of the browseFor... methods to display it.
  42765. @param dialogBoxTitle a text string to display in the dialog box to
  42766. tell the user what's going on
  42767. @param initialFileOrDirectory the file or directory that should be selected when
  42768. the dialog box opens. If this parameter is set to
  42769. File::nonexistent, a sensible default directory
  42770. will be used instead.
  42771. @param filePatternsAllowed a set of file patterns to specify which files can be
  42772. selected - each pattern should be separated by a
  42773. comma or semi-colon, e.g. "*" or "*.jpg;*.gif". An
  42774. empty string means that all files are allowed
  42775. @param useOSNativeDialogBox if true, then a native dialog box will be used if
  42776. possible; if false, then a Juce-based browser dialog
  42777. box will always be used
  42778. @see browseForFileToOpen, browseForFileToSave, browseForDirectory
  42779. */
  42780. FileChooser (const String& dialogBoxTitle,
  42781. const File& initialFileOrDirectory = File::nonexistent,
  42782. const String& filePatternsAllowed = String::empty,
  42783. bool useOSNativeDialogBox = true);
  42784. /** Destructor. */
  42785. ~FileChooser();
  42786. /** Shows a dialog box to choose a file to open.
  42787. This will display the dialog box modally, using an "open file" mode, so that
  42788. it won't allow non-existent files or directories to be chosen.
  42789. @param previewComponent an optional component to display inside the dialog
  42790. box to show special info about the files that the user
  42791. is browsing. The component will not be deleted by this
  42792. object, so the caller must take care of it.
  42793. @returns true if the user selected a file, in which case, use the getResult()
  42794. method to find out what it was. Returns false if they cancelled instead.
  42795. @see browseForFileToSave, browseForDirectory
  42796. */
  42797. bool browseForFileToOpen (FilePreviewComponent* previewComponent = 0);
  42798. /** Same as browseForFileToOpen, but allows the user to select multiple files.
  42799. The files that are returned can be obtained by calling getResults(). See
  42800. browseForFileToOpen() for more info about the behaviour of this method.
  42801. */
  42802. bool browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent = 0);
  42803. /** Shows a dialog box to choose a file to save.
  42804. This will display the dialog box modally, using an "save file" mode, so it
  42805. will allow non-existent files to be chosen, but not directories.
  42806. @param warnAboutOverwritingExistingFiles if true, the dialog box will ask
  42807. the user if they're sure they want to overwrite a file that already
  42808. exists
  42809. @returns true if the user chose a file and pressed 'ok', in which case, use
  42810. the getResult() method to find out what the file was. Returns false
  42811. if they cancelled instead.
  42812. @see browseForFileToOpen, browseForDirectory
  42813. */
  42814. bool browseForFileToSave (bool warnAboutOverwritingExistingFiles);
  42815. /** Shows a dialog box to choose a directory.
  42816. This will display the dialog box modally, using an "open directory" mode, so it
  42817. will only allow directories to be returned, not files.
  42818. @returns true if the user chose a directory and pressed 'ok', in which case, use
  42819. the getResult() method to find out what they chose. Returns false
  42820. if they cancelled instead.
  42821. @see browseForFileToOpen, browseForFileToSave
  42822. */
  42823. bool browseForDirectory();
  42824. /** Same as browseForFileToOpen, but allows the user to select multiple files and directories.
  42825. The files that are returned can be obtained by calling getResults(). See
  42826. browseForFileToOpen() for more info about the behaviour of this method.
  42827. */
  42828. bool browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent = 0);
  42829. /** Returns the last file that was chosen by one of the browseFor methods.
  42830. After calling the appropriate browseFor... method, this method lets you
  42831. find out what file or directory they chose.
  42832. Note that the file returned is only valid if the browse method returned true (i.e.
  42833. if the user pressed 'ok' rather than cancelling).
  42834. If you're using a multiple-file select, then use the getResults() method instead,
  42835. to obtain the list of all files chosen.
  42836. @see getResults
  42837. */
  42838. File getResult() const;
  42839. /** Returns a list of all the files that were chosen during the last call to a
  42840. browse method.
  42841. This array may be empty if no files were chosen, or can contain multiple entries
  42842. if multiple files were chosen.
  42843. @see getResult
  42844. */
  42845. const Array<File>& getResults() const;
  42846. private:
  42847. String title, filters;
  42848. File startingFile;
  42849. Array<File> results;
  42850. bool useNativeDialogBox;
  42851. bool showDialog (bool selectsDirectories, bool selectsFiles, bool isSave,
  42852. bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  42853. FilePreviewComponent* previewComponent);
  42854. static void showPlatformDialog (Array<File>& results, const String& title, const File& file,
  42855. const String& filters, bool selectsDirectories, bool selectsFiles,
  42856. bool isSave, bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  42857. FilePreviewComponent* previewComponent);
  42858. JUCE_LEAK_DETECTOR (FileChooser);
  42859. };
  42860. #endif // __JUCE_FILECHOOSER_JUCEHEADER__
  42861. /*** End of inlined file: juce_FileChooser.h ***/
  42862. #endif
  42863. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  42864. /*** Start of inlined file: juce_FileChooserDialogBox.h ***/
  42865. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  42866. #define __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  42867. /*** Start of inlined file: juce_ResizableWindow.h ***/
  42868. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  42869. #define __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  42870. /*** Start of inlined file: juce_TopLevelWindow.h ***/
  42871. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  42872. #define __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  42873. /*** Start of inlined file: juce_DropShadower.h ***/
  42874. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  42875. #define __JUCE_DROPSHADOWER_JUCEHEADER__
  42876. /**
  42877. Adds a drop-shadow to a component.
  42878. This object creates and manages a set of components which sit around a
  42879. component, creating a gaussian shadow around it. The components will track
  42880. the position of the component and if it's brought to the front they'll also
  42881. follow this.
  42882. For desktop windows you don't need to use this class directly - just
  42883. set the Component::windowHasDropShadow flag when calling
  42884. Component::addToDesktop(), and the system will create one of these if it's
  42885. needed (which it obviously isn't on the Mac, for example).
  42886. */
  42887. class JUCE_API DropShadower : public ComponentListener
  42888. {
  42889. public:
  42890. /** Creates a DropShadower.
  42891. @param alpha the opacity of the shadows, from 0 to 1.0
  42892. @param xOffset the horizontal displacement of the shadow, in pixels
  42893. @param yOffset the vertical displacement of the shadow, in pixels
  42894. @param blurRadius the radius of the blur to use for creating the shadow
  42895. */
  42896. DropShadower (float alpha = 0.5f,
  42897. int xOffset = 1,
  42898. int yOffset = 5,
  42899. float blurRadius = 10.0f);
  42900. /** Destructor. */
  42901. virtual ~DropShadower();
  42902. /** Attaches the DropShadower to the component you want to shadow. */
  42903. void setOwner (Component* componentToFollow);
  42904. /** @internal */
  42905. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  42906. /** @internal */
  42907. void componentBroughtToFront (Component& component);
  42908. /** @internal */
  42909. void componentParentHierarchyChanged (Component& component);
  42910. /** @internal */
  42911. void componentVisibilityChanged (Component& component);
  42912. private:
  42913. Component* owner;
  42914. OwnedArray<Component> shadowWindows;
  42915. Image shadowImageSections[12];
  42916. const int xOffset, yOffset;
  42917. const float alpha, blurRadius;
  42918. bool reentrant;
  42919. void updateShadows();
  42920. void setShadowImage (const Image& src, int num, int w, int h, int sx, int sy);
  42921. void bringShadowWindowsToFront();
  42922. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DropShadower);
  42923. };
  42924. #endif // __JUCE_DROPSHADOWER_JUCEHEADER__
  42925. /*** End of inlined file: juce_DropShadower.h ***/
  42926. /**
  42927. A base class for top-level windows.
  42928. This class is used for components that are considered a major part of your
  42929. application - e.g. ResizableWindow, DocumentWindow, DialogWindow, AlertWindow,
  42930. etc. Things like menus that pop up briefly aren't derived from it.
  42931. A TopLevelWindow is probably on the desktop, but this isn't mandatory - it
  42932. could itself be the child of another component.
  42933. The class manages a list of all instances of top-level windows that are in use,
  42934. and each one is also given the concept of being "active". The active window is
  42935. one that is actively being used by the user. This isn't quite the same as the
  42936. component with the keyboard focus, because there may be a popup menu or other
  42937. temporary window which gets keyboard focus while the active top level window is
  42938. unchanged.
  42939. A top-level window also has an optional drop-shadow.
  42940. @see ResizableWindow, DocumentWindow, DialogWindow
  42941. */
  42942. class JUCE_API TopLevelWindow : public Component
  42943. {
  42944. public:
  42945. /** Creates a TopLevelWindow.
  42946. @param name the name to give the component
  42947. @param addToDesktop if true, the window will be automatically added to the
  42948. desktop; if false, you can use it as a child component
  42949. */
  42950. TopLevelWindow (const String& name, bool addToDesktop);
  42951. /** Destructor. */
  42952. ~TopLevelWindow();
  42953. /** True if this is currently the TopLevelWindow that is actively being used.
  42954. This isn't quite the same as having keyboard focus, because the focus may be
  42955. on a child component or a temporary pop-up menu, etc, while this window is
  42956. still considered to be active.
  42957. @see activeWindowStatusChanged
  42958. */
  42959. bool isActiveWindow() const noexcept { return windowIsActive_; }
  42960. /** This will set the bounds of the window so that it's centred in front of another
  42961. window.
  42962. If your app has a few windows open and want to pop up a dialog box for one of
  42963. them, you can use this to show it in front of the relevent parent window, which
  42964. is a bit neater than just having it appear in the middle of the screen.
  42965. If componentToCentreAround is 0, then the currently active TopLevelWindow will
  42966. be used instead. If no window is focused, it'll just default to the middle of the
  42967. screen.
  42968. */
  42969. void centreAroundComponent (Component* componentToCentreAround,
  42970. int width, int height);
  42971. /** Turns the drop-shadow on and off. */
  42972. void setDropShadowEnabled (bool useShadow);
  42973. /** Sets whether an OS-native title bar will be used, or a Juce one.
  42974. @see isUsingNativeTitleBar
  42975. */
  42976. void setUsingNativeTitleBar (bool useNativeTitleBar);
  42977. /** Returns true if the window is currently using an OS-native title bar.
  42978. @see setUsingNativeTitleBar
  42979. */
  42980. bool isUsingNativeTitleBar() const noexcept { return useNativeTitleBar && isOnDesktop(); }
  42981. /** Returns the number of TopLevelWindow objects currently in use.
  42982. @see getTopLevelWindow
  42983. */
  42984. static int getNumTopLevelWindows() noexcept;
  42985. /** Returns one of the TopLevelWindow objects currently in use.
  42986. The index is 0 to (getNumTopLevelWindows() - 1).
  42987. */
  42988. static TopLevelWindow* getTopLevelWindow (int index) noexcept;
  42989. /** Returns the currently-active top level window.
  42990. There might not be one, of course, so this can return 0.
  42991. */
  42992. static TopLevelWindow* getActiveTopLevelWindow() noexcept;
  42993. /** @internal */
  42994. virtual void addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo = nullptr);
  42995. protected:
  42996. /** This callback happens when this window becomes active or inactive.
  42997. @see isActiveWindow
  42998. */
  42999. virtual void activeWindowStatusChanged();
  43000. /** @internal */
  43001. void focusOfChildComponentChanged (FocusChangeType cause);
  43002. /** @internal */
  43003. void parentHierarchyChanged();
  43004. /** @internal */
  43005. virtual int getDesktopWindowStyleFlags() const;
  43006. /** @internal */
  43007. void recreateDesktopWindow();
  43008. /** @internal */
  43009. void visibilityChanged();
  43010. private:
  43011. friend class TopLevelWindowManager;
  43012. bool useDropShadow, useNativeTitleBar, windowIsActive_;
  43013. ScopedPointer <DropShadower> shadower;
  43014. void setWindowActive (bool isNowActive);
  43015. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TopLevelWindow);
  43016. };
  43017. #endif // __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  43018. /*** End of inlined file: juce_TopLevelWindow.h ***/
  43019. /*** Start of inlined file: juce_ComponentDragger.h ***/
  43020. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  43021. #define __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  43022. /*** Start of inlined file: juce_ComponentBoundsConstrainer.h ***/
  43023. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  43024. #define __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  43025. /**
  43026. A class that imposes restrictions on a Component's size or position.
  43027. This is used by classes such as ResizableCornerComponent,
  43028. ResizableBorderComponent and ResizableWindow.
  43029. The base class can impose some basic size and position limits, but you can
  43030. also subclass this for custom uses.
  43031. @see ResizableCornerComponent, ResizableBorderComponent, ResizableWindow
  43032. */
  43033. class JUCE_API ComponentBoundsConstrainer
  43034. {
  43035. public:
  43036. /** When first created, the object will not impose any restrictions on the components. */
  43037. ComponentBoundsConstrainer() noexcept;
  43038. /** Destructor. */
  43039. virtual ~ComponentBoundsConstrainer();
  43040. /** Imposes a minimum width limit. */
  43041. void setMinimumWidth (int minimumWidth) noexcept;
  43042. /** Returns the current minimum width. */
  43043. int getMinimumWidth() const noexcept { return minW; }
  43044. /** Imposes a maximum width limit. */
  43045. void setMaximumWidth (int maximumWidth) noexcept;
  43046. /** Returns the current maximum width. */
  43047. int getMaximumWidth() const noexcept { return maxW; }
  43048. /** Imposes a minimum height limit. */
  43049. void setMinimumHeight (int minimumHeight) noexcept;
  43050. /** Returns the current minimum height. */
  43051. int getMinimumHeight() const noexcept { return minH; }
  43052. /** Imposes a maximum height limit. */
  43053. void setMaximumHeight (int maximumHeight) noexcept;
  43054. /** Returns the current maximum height. */
  43055. int getMaximumHeight() const noexcept { return maxH; }
  43056. /** Imposes a minimum width and height limit. */
  43057. void setMinimumSize (int minimumWidth,
  43058. int minimumHeight) noexcept;
  43059. /** Imposes a maximum width and height limit. */
  43060. void setMaximumSize (int maximumWidth,
  43061. int maximumHeight) noexcept;
  43062. /** Set all the maximum and minimum dimensions. */
  43063. void setSizeLimits (int minimumWidth,
  43064. int minimumHeight,
  43065. int maximumWidth,
  43066. int maximumHeight) noexcept;
  43067. /** Sets the amount by which the component is allowed to go off-screen.
  43068. The values indicate how many pixels must remain on-screen when dragged off
  43069. one of its parent's edges, so e.g. if minimumWhenOffTheTop is set to 10, then
  43070. when the component goes off the top of the screen, its y-position will be
  43071. clipped so that there are always at least 10 pixels on-screen. In other words,
  43072. the lowest y-position it can take would be (10 - the component's height).
  43073. If you pass 0 or less for one of these amounts, the component is allowed
  43074. to move beyond that edge completely, with no restrictions at all.
  43075. If you pass a very large number (i.e. larger that the dimensions of the
  43076. component itself), then the component won't be allowed to overlap that
  43077. edge at all. So e.g. setting minimumWhenOffTheLeft to 0xffffff will mean that
  43078. the component will bump into the left side of the screen and go no further.
  43079. */
  43080. void setMinimumOnscreenAmounts (int minimumWhenOffTheTop,
  43081. int minimumWhenOffTheLeft,
  43082. int minimumWhenOffTheBottom,
  43083. int minimumWhenOffTheRight) noexcept;
  43084. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  43085. int getMinimumWhenOffTheTop() const noexcept { return minOffTop; }
  43086. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  43087. int getMinimumWhenOffTheLeft() const noexcept { return minOffLeft; }
  43088. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  43089. int getMinimumWhenOffTheBottom() const noexcept { return minOffBottom; }
  43090. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  43091. int getMinimumWhenOffTheRight() const noexcept { return minOffRight; }
  43092. /** Specifies a width-to-height ratio that the resizer should always maintain.
  43093. If the value is 0, no aspect ratio is enforced. If it's non-zero, the width
  43094. will always be maintained as this multiple of the height.
  43095. @see setResizeLimits
  43096. */
  43097. void setFixedAspectRatio (double widthOverHeight) noexcept;
  43098. /** Returns the aspect ratio that was set with setFixedAspectRatio().
  43099. If no aspect ratio is being enforced, this will return 0.
  43100. */
  43101. double getFixedAspectRatio() const noexcept;
  43102. /** This callback changes the given co-ordinates to impose whatever the current
  43103. constraints are set to be.
  43104. @param bounds the target position that should be examined and adjusted
  43105. @param previousBounds the component's current size
  43106. @param limits the region in which the component can be positioned
  43107. @param isStretchingTop whether the top edge of the component is being resized
  43108. @param isStretchingLeft whether the left edge of the component is being resized
  43109. @param isStretchingBottom whether the bottom edge of the component is being resized
  43110. @param isStretchingRight whether the right edge of the component is being resized
  43111. */
  43112. virtual void checkBounds (Rectangle<int>& bounds,
  43113. const Rectangle<int>& previousBounds,
  43114. const Rectangle<int>& limits,
  43115. bool isStretchingTop,
  43116. bool isStretchingLeft,
  43117. bool isStretchingBottom,
  43118. bool isStretchingRight);
  43119. /** This callback happens when the resizer is about to start dragging. */
  43120. virtual void resizeStart();
  43121. /** This callback happens when the resizer has finished dragging. */
  43122. virtual void resizeEnd();
  43123. /** Checks the given bounds, and then sets the component to the corrected size. */
  43124. void setBoundsForComponent (Component* component,
  43125. const Rectangle<int>& bounds,
  43126. bool isStretchingTop,
  43127. bool isStretchingLeft,
  43128. bool isStretchingBottom,
  43129. bool isStretchingRight);
  43130. /** Performs a check on the current size of a component, and moves or resizes
  43131. it if it fails the constraints.
  43132. */
  43133. void checkComponentBounds (Component* component);
  43134. /** Called by setBoundsForComponent() to apply a new constrained size to a
  43135. component.
  43136. By default this just calls setBounds(), but it virtual in case it's needed for
  43137. extremely cunning purposes.
  43138. */
  43139. virtual void applyBoundsToComponent (Component* component,
  43140. const Rectangle<int>& bounds);
  43141. private:
  43142. int minW, maxW, minH, maxH;
  43143. int minOffTop, minOffLeft, minOffBottom, minOffRight;
  43144. double aspectRatio;
  43145. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentBoundsConstrainer);
  43146. };
  43147. #endif // __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  43148. /*** End of inlined file: juce_ComponentBoundsConstrainer.h ***/
  43149. /**
  43150. An object to take care of the logic for dragging components around with the mouse.
  43151. Very easy to use - in your mouseDown() callback, call startDraggingComponent(),
  43152. then in your mouseDrag() callback, call dragComponent().
  43153. When starting a drag, you can give it a ComponentBoundsConstrainer to use
  43154. to limit the component's position and keep it on-screen.
  43155. e.g. @code
  43156. class MyDraggableComp
  43157. {
  43158. ComponentDragger myDragger;
  43159. void mouseDown (const MouseEvent& e)
  43160. {
  43161. myDragger.startDraggingComponent (this, e);
  43162. }
  43163. void mouseDrag (const MouseEvent& e)
  43164. {
  43165. myDragger.dragComponent (this, e, nullptr);
  43166. }
  43167. };
  43168. @endcode
  43169. */
  43170. class JUCE_API ComponentDragger
  43171. {
  43172. public:
  43173. /** Creates a ComponentDragger. */
  43174. ComponentDragger();
  43175. /** Destructor. */
  43176. virtual ~ComponentDragger();
  43177. /** Call this from your component's mouseDown() method, to prepare for dragging.
  43178. @param componentToDrag the component that you want to drag
  43179. @param e the mouse event that is triggering the drag
  43180. @see dragComponent
  43181. */
  43182. void startDraggingComponent (Component* componentToDrag,
  43183. const MouseEvent& e);
  43184. /** Call this from your mouseDrag() callback to move the component.
  43185. This will move the component, but will first check the validity of the
  43186. component's new position using the checkPosition() method, which you
  43187. can override if you need to enforce special positioning limits on the
  43188. component.
  43189. @param componentToDrag the component that you want to drag
  43190. @param e the current mouse-drag event
  43191. @param constrainer an optional constrainer object that should be used
  43192. to apply limits to the component's position. Pass
  43193. null if you don't want to contrain the movement.
  43194. @see startDraggingComponent
  43195. */
  43196. void dragComponent (Component* componentToDrag,
  43197. const MouseEvent& e,
  43198. ComponentBoundsConstrainer* constrainer);
  43199. private:
  43200. Point<int> mouseDownWithinTarget;
  43201. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentDragger);
  43202. };
  43203. #endif // __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  43204. /*** End of inlined file: juce_ComponentDragger.h ***/
  43205. /*** Start of inlined file: juce_ResizableBorderComponent.h ***/
  43206. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  43207. #define __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  43208. /**
  43209. A component that resizes its parent component when dragged.
  43210. This component forms a frame around the edge of a component, allowing it to
  43211. be dragged by the edges or corners to resize it - like the way windows are
  43212. resized in MSWindows or Linux.
  43213. To use it, just add it to your component, making it fill the entire parent component
  43214. (there's a mouse hit-test that only traps mouse-events which land around the
  43215. edge of the component, so it's even ok to put it on top of any other components
  43216. you're using). Make sure you rescale the resizer component to fill the parent
  43217. each time the parent's size changes.
  43218. @see ResizableCornerComponent
  43219. */
  43220. class JUCE_API ResizableBorderComponent : public Component
  43221. {
  43222. public:
  43223. /** Creates a resizer.
  43224. Pass in the target component which you want to be resized when this one is
  43225. dragged.
  43226. The target component will usually be a parent of the resizer component, but this
  43227. isn't mandatory.
  43228. Remember that when the target component is resized, it'll need to move and
  43229. resize this component to keep it in place, as this won't happen automatically.
  43230. If the constrainer parameter is non-zero, then this object will be used to enforce
  43231. limits on the size and position that the component can be stretched to. Make sure
  43232. that the constrainer isn't deleted while still in use by this object.
  43233. @see ComponentBoundsConstrainer
  43234. */
  43235. ResizableBorderComponent (Component* componentToResize,
  43236. ComponentBoundsConstrainer* constrainer);
  43237. /** Destructor. */
  43238. ~ResizableBorderComponent();
  43239. /** Specifies how many pixels wide the draggable edges of this component are.
  43240. @see getBorderThickness
  43241. */
  43242. void setBorderThickness (const BorderSize<int>& newBorderSize);
  43243. /** Returns the number of pixels wide that the draggable edges of this component are.
  43244. @see setBorderThickness
  43245. */
  43246. const BorderSize<int> getBorderThickness() const;
  43247. /** Represents the different sections of a resizable border, which allow it to
  43248. resized in different ways.
  43249. */
  43250. class Zone
  43251. {
  43252. public:
  43253. enum Zones
  43254. {
  43255. centre = 0,
  43256. left = 1,
  43257. top = 2,
  43258. right = 4,
  43259. bottom = 8
  43260. };
  43261. /** Creates a Zone from a combination of the flags in \enum Zones. */
  43262. explicit Zone (int zoneFlags = 0) noexcept;
  43263. Zone (const Zone& other) noexcept;
  43264. Zone& operator= (const Zone& other) noexcept;
  43265. bool operator== (const Zone& other) const noexcept;
  43266. bool operator!= (const Zone& other) const noexcept;
  43267. /** Given a point within a rectangle with a resizable border, this returns the
  43268. zone that the point lies within.
  43269. */
  43270. static const Zone fromPositionOnBorder (const Rectangle<int>& totalSize,
  43271. const BorderSize<int>& border,
  43272. const Point<int>& position);
  43273. /** Returns an appropriate mouse-cursor for this resize zone. */
  43274. const MouseCursor getMouseCursor() const noexcept;
  43275. /** Returns true if dragging this zone will move the enire object without resizing it. */
  43276. bool isDraggingWholeObject() const noexcept { return zone == centre; }
  43277. /** Returns true if dragging this zone will move the object's left edge. */
  43278. bool isDraggingLeftEdge() const noexcept { return (zone & left) != 0; }
  43279. /** Returns true if dragging this zone will move the object's right edge. */
  43280. bool isDraggingRightEdge() const noexcept { return (zone & right) != 0; }
  43281. /** Returns true if dragging this zone will move the object's top edge. */
  43282. bool isDraggingTopEdge() const noexcept { return (zone & top) != 0; }
  43283. /** Returns true if dragging this zone will move the object's bottom edge. */
  43284. bool isDraggingBottomEdge() const noexcept { return (zone & bottom) != 0; }
  43285. /** Resizes this rectangle by the given amount, moving just the edges that this zone
  43286. applies to.
  43287. */
  43288. template <typename ValueType>
  43289. const Rectangle<ValueType> resizeRectangleBy (Rectangle<ValueType> original,
  43290. const Point<ValueType>& distance) const noexcept
  43291. {
  43292. if (isDraggingWholeObject())
  43293. return original + distance;
  43294. if (isDraggingLeftEdge())
  43295. original.setLeft (jmin (original.getRight(), original.getX() + distance.getX()));
  43296. if (isDraggingRightEdge())
  43297. original.setWidth (jmax (ValueType(), original.getWidth() + distance.getX()));
  43298. if (isDraggingTopEdge())
  43299. original.setTop (jmin (original.getBottom(), original.getY() + distance.getY()));
  43300. if (isDraggingBottomEdge())
  43301. original.setHeight (jmax (ValueType(), original.getHeight() + distance.getY()));
  43302. return original;
  43303. }
  43304. /** Returns the raw flags for this zone. */
  43305. int getZoneFlags() const noexcept { return zone; }
  43306. private:
  43307. int zone;
  43308. };
  43309. protected:
  43310. /** @internal */
  43311. void paint (Graphics& g);
  43312. /** @internal */
  43313. void mouseEnter (const MouseEvent& e);
  43314. /** @internal */
  43315. void mouseMove (const MouseEvent& e);
  43316. /** @internal */
  43317. void mouseDown (const MouseEvent& e);
  43318. /** @internal */
  43319. void mouseDrag (const MouseEvent& e);
  43320. /** @internal */
  43321. void mouseUp (const MouseEvent& e);
  43322. /** @internal */
  43323. bool hitTest (int x, int y);
  43324. private:
  43325. WeakReference<Component> component;
  43326. ComponentBoundsConstrainer* constrainer;
  43327. BorderSize<int> borderSize;
  43328. Rectangle<int> originalBounds;
  43329. Zone mouseZone;
  43330. void updateMouseZone (const MouseEvent& e);
  43331. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableBorderComponent);
  43332. };
  43333. #endif // __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  43334. /*** End of inlined file: juce_ResizableBorderComponent.h ***/
  43335. /*** Start of inlined file: juce_ResizableCornerComponent.h ***/
  43336. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  43337. #define __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  43338. /** A component that resizes a parent component when dragged.
  43339. This is the small triangular stripey resizer component you get in the bottom-right
  43340. of windows (more commonly on the Mac than Windows). Put one in the corner of
  43341. a larger component and it will automatically resize its parent when it gets dragged
  43342. around.
  43343. @see ResizableFrameComponent
  43344. */
  43345. class JUCE_API ResizableCornerComponent : public Component
  43346. {
  43347. public:
  43348. /** Creates a resizer.
  43349. Pass in the target component which you want to be resized when this one is
  43350. dragged.
  43351. The target component will usually be a parent of the resizer component, but this
  43352. isn't mandatory.
  43353. Remember that when the target component is resized, it'll need to move and
  43354. resize this component to keep it in place, as this won't happen automatically.
  43355. If the constrainer parameter is non-zero, then this object will be used to enforce
  43356. limits on the size and position that the component can be stretched to. Make sure
  43357. that the constrainer isn't deleted while still in use by this object. If you
  43358. pass a zero in here, no limits will be put on the sizes it can be stretched to.
  43359. @see ComponentBoundsConstrainer
  43360. */
  43361. ResizableCornerComponent (Component* componentToResize,
  43362. ComponentBoundsConstrainer* constrainer);
  43363. /** Destructor. */
  43364. ~ResizableCornerComponent();
  43365. protected:
  43366. /** @internal */
  43367. void paint (Graphics& g);
  43368. /** @internal */
  43369. void mouseDown (const MouseEvent& e);
  43370. /** @internal */
  43371. void mouseDrag (const MouseEvent& e);
  43372. /** @internal */
  43373. void mouseUp (const MouseEvent& e);
  43374. /** @internal */
  43375. bool hitTest (int x, int y);
  43376. private:
  43377. WeakReference<Component> component;
  43378. ComponentBoundsConstrainer* constrainer;
  43379. Rectangle<int> originalBounds;
  43380. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableCornerComponent);
  43381. };
  43382. #endif // __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  43383. /*** End of inlined file: juce_ResizableCornerComponent.h ***/
  43384. /**
  43385. A base class for top-level windows that can be dragged around and resized.
  43386. To add content to the window, use its setContentOwned() or setContentNonOwned() methods
  43387. to give it a component that will remain positioned inside it (leaving a gap around
  43388. the edges for a border).
  43389. It's not advisable to add child components directly to a ResizableWindow: put them
  43390. inside your content component instead. And overriding methods like resized(), moved(), etc
  43391. is also not recommended - instead override these methods for your content component.
  43392. (If for some obscure reason you do need to override these methods, always remember to
  43393. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  43394. decorations correctly).
  43395. By default resizing isn't enabled - use the setResizable() method to enable it and
  43396. to choose the style of resizing to use.
  43397. @see TopLevelWindow
  43398. */
  43399. class JUCE_API ResizableWindow : public TopLevelWindow
  43400. {
  43401. public:
  43402. /** Creates a ResizableWindow.
  43403. This constructor doesn't specify a background colour, so the LookAndFeel's default
  43404. background colour will be used.
  43405. @param name the name to give the component
  43406. @param addToDesktop if true, the window will be automatically added to the
  43407. desktop; if false, you can use it as a child component
  43408. */
  43409. ResizableWindow (const String& name,
  43410. bool addToDesktop);
  43411. /** Creates a ResizableWindow.
  43412. @param name the name to give the component
  43413. @param backgroundColour the colour to use for filling the window's background.
  43414. @param addToDesktop if true, the window will be automatically added to the
  43415. desktop; if false, you can use it as a child component
  43416. */
  43417. ResizableWindow (const String& name,
  43418. const Colour& backgroundColour,
  43419. bool addToDesktop);
  43420. /** Destructor.
  43421. If a content component has been set with setContentOwned(), it will be deleted.
  43422. */
  43423. ~ResizableWindow();
  43424. /** Returns the colour currently being used for the window's background.
  43425. As a convenience the window will fill itself with this colour, but you
  43426. can override the paint() method if you need more customised behaviour.
  43427. This method is the same as retrieving the colour for ResizableWindow::backgroundColourId.
  43428. @see setBackgroundColour
  43429. */
  43430. const Colour getBackgroundColour() const noexcept;
  43431. /** Changes the colour currently being used for the window's background.
  43432. As a convenience the window will fill itself with this colour, but you
  43433. can override the paint() method if you need more customised behaviour.
  43434. Note that the opaque state of this window is altered by this call to reflect
  43435. the opacity of the colour passed-in. On window systems which can't support
  43436. semi-transparent windows this might cause problems, (though it's unlikely you'll
  43437. be using this class as a base for a semi-transparent component anyway).
  43438. You can also use the ResizableWindow::backgroundColourId colour id to set
  43439. this colour.
  43440. @see getBackgroundColour
  43441. */
  43442. void setBackgroundColour (const Colour& newColour);
  43443. /** Make the window resizable or fixed.
  43444. @param shouldBeResizable whether it's resizable at all
  43445. @param useBottomRightCornerResizer if true, it'll add a ResizableCornerComponent at the
  43446. bottom-right; if false, it'll use a ResizableBorderComponent
  43447. around the edge
  43448. @see setResizeLimits, isResizable
  43449. */
  43450. void setResizable (bool shouldBeResizable,
  43451. bool useBottomRightCornerResizer);
  43452. /** True if resizing is enabled.
  43453. @see setResizable
  43454. */
  43455. bool isResizable() const noexcept;
  43456. /** This sets the maximum and minimum sizes for the window.
  43457. If the window's current size is outside these limits, it will be resized to
  43458. make sure it's within them.
  43459. Calling setBounds() on the component will bypass any size checking - it's only when
  43460. the window is being resized by the user that these values are enforced.
  43461. @see setResizable, setFixedAspectRatio
  43462. */
  43463. void setResizeLimits (int newMinimumWidth,
  43464. int newMinimumHeight,
  43465. int newMaximumWidth,
  43466. int newMaximumHeight) noexcept;
  43467. /** Returns the bounds constrainer object that this window is using.
  43468. You can access this to change its properties.
  43469. */
  43470. ComponentBoundsConstrainer* getConstrainer() noexcept { return constrainer; }
  43471. /** Sets the bounds-constrainer object to use for resizing and dragging this window.
  43472. A pointer to the object you pass in will be kept, but it won't be deleted
  43473. by this object, so it's the caller's responsiblity to manage it.
  43474. If you pass 0, then no contraints will be placed on the positioning of the window.
  43475. */
  43476. void setConstrainer (ComponentBoundsConstrainer* newConstrainer);
  43477. /** Calls the window's setBounds method, after first checking these bounds
  43478. with the current constrainer.
  43479. @see setConstrainer
  43480. */
  43481. void setBoundsConstrained (const Rectangle<int>& bounds);
  43482. /** Returns true if the window is currently in full-screen mode.
  43483. @see setFullScreen
  43484. */
  43485. bool isFullScreen() const;
  43486. /** Puts the window into full-screen mode, or restores it to its normal size.
  43487. If true, the window will become full-screen; if false, it will return to the
  43488. last size it was before being made full-screen.
  43489. @see isFullScreen
  43490. */
  43491. void setFullScreen (bool shouldBeFullScreen);
  43492. /** Returns true if the window is currently minimised.
  43493. @see setMinimised
  43494. */
  43495. bool isMinimised() const;
  43496. /** Minimises the window, or restores it to its previous position and size.
  43497. When being un-minimised, it'll return to the last position and size it
  43498. was in before being minimised.
  43499. @see isMinimised
  43500. */
  43501. void setMinimised (bool shouldMinimise);
  43502. /** Adds the window to the desktop using the default flags. */
  43503. void addToDesktop();
  43504. /** Returns a string which encodes the window's current size and position.
  43505. This string will encapsulate the window's size, position, and whether it's
  43506. in full-screen mode. It's intended for letting your application save and
  43507. restore a window's position.
  43508. Use the restoreWindowStateFromString() to restore from a saved state.
  43509. @see restoreWindowStateFromString
  43510. */
  43511. String getWindowStateAsString();
  43512. /** Restores the window to a previously-saved size and position.
  43513. This restores the window's size, positon and full-screen status from an
  43514. string that was previously created with the getWindowStateAsString()
  43515. method.
  43516. @returns false if the string wasn't a valid window state
  43517. @see getWindowStateAsString
  43518. */
  43519. bool restoreWindowStateFromString (const String& previousState);
  43520. /** Returns the current content component.
  43521. This will be the component set by setContentOwned() or setContentNonOwned, or 0 if none
  43522. has yet been specified.
  43523. @see setContentOwned, setContentNonOwned
  43524. */
  43525. Component* getContentComponent() const noexcept { return contentComponent; }
  43526. /** Changes the current content component.
  43527. This sets a component that will be placed in the centre of the ResizableWindow,
  43528. (leaving a space around the edge for the border).
  43529. You should never add components directly to a ResizableWindow (or any of its subclasses)
  43530. with addChildComponent(). Instead, add them to the content component.
  43531. @param newContentComponent the new component to use - this component will be deleted when it's
  43532. no longer needed (i.e. when the window is deleted or a new content
  43533. component is set for it). To set a component that this window will not
  43534. delete, call setContentNonOwned() instead.
  43535. @param resizeToFitWhenContentChangesSize if true, then the ResizableWindow will maintain its size
  43536. such that it always fits around the size of the content component. If false,
  43537. the new content will be resized to fit the current space available.
  43538. */
  43539. void setContentOwned (Component* newContentComponent,
  43540. bool resizeToFitWhenContentChangesSize);
  43541. /** Changes the current content component.
  43542. This sets a component that will be placed in the centre of the ResizableWindow,
  43543. (leaving a space around the edge for the border).
  43544. You should never add components directly to a ResizableWindow (or any of its subclasses)
  43545. with addChildComponent(). Instead, add them to the content component.
  43546. @param newContentComponent the new component to use - this component will NOT be deleted by this
  43547. component, so it's the caller's responsibility to manage its lifetime (it's
  43548. ok to delete it while this window is still using it). To set a content
  43549. component that the window will delete, call setContentOwned() instead.
  43550. @param resizeToFitWhenContentChangesSize if true, then the ResizableWindow will maintain its size
  43551. such that it always fits around the size of the content component. If false,
  43552. the new content will be resized to fit the current space available.
  43553. */
  43554. void setContentNonOwned (Component* newContentComponent,
  43555. bool resizeToFitWhenContentChangesSize);
  43556. /** Removes the current content component.
  43557. If the previous content component was added with setContentOwned(), it will also be deleted. If
  43558. it was added with setContentNonOwned(), it will simply be removed from this component.
  43559. */
  43560. void clearContentComponent();
  43561. /** Changes the window so that the content component ends up with the specified size.
  43562. This is basically a setSize call on the window, but which adds on the borders,
  43563. so you can specify the content component's target size.
  43564. */
  43565. void setContentComponentSize (int width, int height);
  43566. /** Returns the width of the frame to use around the window.
  43567. @see getContentComponentBorder
  43568. */
  43569. virtual const BorderSize<int> getBorderThickness();
  43570. /** Returns the insets to use when positioning the content component.
  43571. @see getBorderThickness
  43572. */
  43573. virtual const BorderSize<int> getContentComponentBorder();
  43574. /** A set of colour IDs to use to change the colour of various aspects of the window.
  43575. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  43576. methods.
  43577. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  43578. */
  43579. enum ColourIds
  43580. {
  43581. backgroundColourId = 0x1005700, /**< A colour to use to fill the window's background. */
  43582. };
  43583. /** @deprecated - use setContentOwned() and setContentNonOwned() instead. */
  43584. JUCE_DEPRECATED (void setContentComponent (Component* newContentComponent,
  43585. bool deleteOldOne = true,
  43586. bool resizeToFit = false));
  43587. protected:
  43588. /** @internal */
  43589. void paint (Graphics& g);
  43590. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  43591. void moved();
  43592. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  43593. void resized();
  43594. /** @internal */
  43595. void mouseDown (const MouseEvent& e);
  43596. /** @internal */
  43597. void mouseDrag (const MouseEvent& e);
  43598. /** @internal */
  43599. void lookAndFeelChanged();
  43600. /** @internal */
  43601. void childBoundsChanged (Component* child);
  43602. /** @internal */
  43603. void parentSizeChanged();
  43604. /** @internal */
  43605. void visibilityChanged();
  43606. /** @internal */
  43607. void activeWindowStatusChanged();
  43608. /** @internal */
  43609. int getDesktopWindowStyleFlags() const;
  43610. #if JUCE_DEBUG
  43611. /** Overridden to warn people about adding components directly to this component
  43612. instead of using setContentOwned().
  43613. If you know what you're doing and are sure you really want to add a component, specify
  43614. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  43615. */
  43616. void addChildComponent (Component* child, int zOrder = -1);
  43617. /** Overridden to warn people about adding components directly to this component
  43618. instead of using setContentOwned().
  43619. If you know what you're doing and are sure you really want to add a component, specify
  43620. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  43621. */
  43622. void addAndMakeVisible (Component* child, int zOrder = -1);
  43623. #endif
  43624. ScopedPointer <ResizableCornerComponent> resizableCorner;
  43625. ScopedPointer <ResizableBorderComponent> resizableBorder;
  43626. private:
  43627. Component::SafePointer <Component> contentComponent;
  43628. bool ownsContentComponent, resizeToFitContent, fullscreen;
  43629. ComponentDragger dragger;
  43630. Rectangle<int> lastNonFullScreenPos;
  43631. ComponentBoundsConstrainer defaultConstrainer;
  43632. ComponentBoundsConstrainer* constrainer;
  43633. #if JUCE_DEBUG
  43634. bool hasBeenResized;
  43635. #endif
  43636. void initialise (bool addToDesktop);
  43637. void updateLastPos();
  43638. void setContent (Component* newComp, bool takeOwnership, bool resizeToFit);
  43639. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  43640. // The parameters for these methods have changed - please update your code!
  43641. JUCE_DEPRECATED (void getBorderThickness (int& left, int& top, int& right, int& bottom));
  43642. JUCE_DEPRECATED (void getContentComponentBorder (int& left, int& top, int& right, int& bottom));
  43643. #endif
  43644. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableWindow);
  43645. };
  43646. #endif // __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  43647. /*** End of inlined file: juce_ResizableWindow.h ***/
  43648. /*** Start of inlined file: juce_GlyphArrangement.h ***/
  43649. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  43650. #define __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  43651. /**
  43652. A glyph from a particular font, with a particular size, style,
  43653. typeface and position.
  43654. You should rarely need to use this class directly - for most purposes, the
  43655. GlyphArrangement class will do what you need for text layout.
  43656. @see GlyphArrangement, Font
  43657. */
  43658. class JUCE_API PositionedGlyph
  43659. {
  43660. public:
  43661. PositionedGlyph (const Font& font, juce_wchar character, int glyphNumber,
  43662. float anchorX, float baselineY, float width, bool isWhitespace);
  43663. PositionedGlyph (const PositionedGlyph& other);
  43664. PositionedGlyph& operator= (const PositionedGlyph& other);
  43665. ~PositionedGlyph();
  43666. /** Returns the character the glyph represents. */
  43667. juce_wchar getCharacter() const noexcept { return character; }
  43668. /** Checks whether the glyph is actually empty. */
  43669. bool isWhitespace() const noexcept { return whitespace; }
  43670. /** Returns the position of the glyph's left-hand edge. */
  43671. float getLeft() const noexcept { return x; }
  43672. /** Returns the position of the glyph's right-hand edge. */
  43673. float getRight() const noexcept { return x + w; }
  43674. /** Returns the y position of the glyph's baseline. */
  43675. float getBaselineY() const noexcept { return y; }
  43676. /** Returns the y position of the top of the glyph. */
  43677. float getTop() const { return y - font.getAscent(); }
  43678. /** Returns the y position of the bottom of the glyph. */
  43679. float getBottom() const { return y + font.getDescent(); }
  43680. /** Returns the bounds of the glyph. */
  43681. const Rectangle<float> getBounds() const { return Rectangle<float> (x, getTop(), w, font.getHeight()); }
  43682. /** Shifts the glyph's position by a relative amount. */
  43683. void moveBy (float deltaX, float deltaY);
  43684. /** Draws the glyph into a graphics context. */
  43685. void draw (const Graphics& g) const;
  43686. /** Draws the glyph into a graphics context, with an extra transform applied to it. */
  43687. void draw (const Graphics& g, const AffineTransform& transform) const;
  43688. /** Returns the path for this glyph.
  43689. @param path the glyph's outline will be appended to this path
  43690. */
  43691. void createPath (Path& path) const;
  43692. /** Checks to see if a point lies within this glyph. */
  43693. bool hitTest (float x, float y) const;
  43694. private:
  43695. friend class GlyphArrangement;
  43696. Font font;
  43697. juce_wchar character;
  43698. int glyph;
  43699. float x, y, w;
  43700. bool whitespace;
  43701. JUCE_LEAK_DETECTOR (PositionedGlyph);
  43702. };
  43703. /**
  43704. A set of glyphs, each with a position.
  43705. You can create a GlyphArrangement, text to it and then draw it onto a
  43706. graphics context. It's used internally by the text methods in the
  43707. Graphics class, but can be used directly if more control is needed.
  43708. @see Font, PositionedGlyph
  43709. */
  43710. class JUCE_API GlyphArrangement
  43711. {
  43712. public:
  43713. /** Creates an empty arrangement. */
  43714. GlyphArrangement();
  43715. /** Takes a copy of another arrangement. */
  43716. GlyphArrangement (const GlyphArrangement& other);
  43717. /** Copies another arrangement onto this one.
  43718. To add another arrangement without clearing this one, use addGlyphArrangement().
  43719. */
  43720. GlyphArrangement& operator= (const GlyphArrangement& other);
  43721. /** Destructor. */
  43722. ~GlyphArrangement();
  43723. /** Returns the total number of glyphs in the arrangement. */
  43724. int getNumGlyphs() const noexcept { return glyphs.size(); }
  43725. /** Returns one of the glyphs from the arrangement.
  43726. @param index the glyph's index, from 0 to (getNumGlyphs() - 1). Be
  43727. careful not to pass an out-of-range index here, as it
  43728. doesn't do any bounds-checking.
  43729. */
  43730. PositionedGlyph& getGlyph (int index) const;
  43731. /** Clears all text from the arrangement and resets it.
  43732. */
  43733. void clear();
  43734. /** Appends a line of text to the arrangement.
  43735. This will add the text as a single line, where x is the left-hand edge of the
  43736. first character, and y is the position for the text's baseline.
  43737. If the text contains new-lines or carriage-returns, this will ignore them - use
  43738. addJustifiedText() to add multi-line arrangements.
  43739. */
  43740. void addLineOfText (const Font& font,
  43741. const String& text,
  43742. float x, float y);
  43743. /** Adds a line of text, truncating it if it's wider than a specified size.
  43744. This is the same as addLineOfText(), but if the line's width exceeds the value
  43745. specified in maxWidthPixels, it will be truncated using either ellipsis (i.e. dots: "..."),
  43746. if useEllipsis is true, or if this is false, it will just drop any subsequent characters.
  43747. */
  43748. void addCurtailedLineOfText (const Font& font,
  43749. const String& text,
  43750. float x, float y,
  43751. float maxWidthPixels,
  43752. bool useEllipsis);
  43753. /** Adds some multi-line text, breaking lines at word-boundaries if they are too wide.
  43754. This will add text to the arrangement, breaking it into new lines either where there
  43755. is a new-line or carriage-return character in the text, or where a line's width
  43756. exceeds the value set in maxLineWidth.
  43757. Each line that is added will be laid out using the flags set in horizontalLayout, so
  43758. the lines can be left- or right-justified, or centred horizontally in the space
  43759. between x and (x + maxLineWidth).
  43760. The y co-ordinate is the position of the baseline of the first line of text - subsequent
  43761. lines will be placed below it, separated by a distance of font.getHeight().
  43762. */
  43763. void addJustifiedText (const Font& font,
  43764. const String& text,
  43765. float x, float y,
  43766. float maxLineWidth,
  43767. const Justification& horizontalLayout);
  43768. /** Tries to fit some text withing a given space.
  43769. This does its best to make the given text readable within the specified rectangle,
  43770. so it useful for labelling things.
  43771. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  43772. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  43773. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  43774. it's been truncated.
  43775. A Justification parameter lets you specify how the text is laid out within the rectangle,
  43776. both horizontally and vertically.
  43777. @see Graphics::drawFittedText
  43778. */
  43779. void addFittedText (const Font& font,
  43780. const String& text,
  43781. float x, float y, float width, float height,
  43782. const Justification& layout,
  43783. int maximumLinesToUse,
  43784. float minimumHorizontalScale = 0.7f);
  43785. /** Appends another glyph arrangement to this one. */
  43786. void addGlyphArrangement (const GlyphArrangement& other);
  43787. /** Appends a custom glyph to the arrangement. */
  43788. void addGlyph (const PositionedGlyph& glyph);
  43789. /** Draws this glyph arrangement to a graphics context.
  43790. This uses cached bitmaps so is much faster than the draw (Graphics&, const AffineTransform&)
  43791. method, which renders the glyphs as filled vectors.
  43792. */
  43793. void draw (const Graphics& g) const;
  43794. /** Draws this glyph arrangement to a graphics context.
  43795. This renders the paths as filled vectors, so is far slower than the draw (Graphics&)
  43796. method for non-transformed arrangements.
  43797. */
  43798. void draw (const Graphics& g, const AffineTransform& transform) const;
  43799. /** Converts the set of glyphs into a path.
  43800. @param path the glyphs' outlines will be appended to this path
  43801. */
  43802. void createPath (Path& path) const;
  43803. /** Looks for a glyph that contains the given co-ordinate.
  43804. @returns the index of the glyph, or -1 if none were found.
  43805. */
  43806. int findGlyphIndexAt (float x, float y) const;
  43807. /** Finds the smallest rectangle that will enclose a subset of the glyphs.
  43808. @param startIndex the first glyph to test
  43809. @param numGlyphs the number of glyphs to include; if this is < 0, all glyphs after
  43810. startIndex will be included
  43811. @param includeWhitespace if true, the extent of any whitespace characters will also
  43812. be taken into account
  43813. */
  43814. const Rectangle<float> getBoundingBox (int startIndex, int numGlyphs, bool includeWhitespace) const;
  43815. /** Shifts a set of glyphs by a given amount.
  43816. @param startIndex the first glyph to transform
  43817. @param numGlyphs the number of glyphs to move; if this is < 0, all glyphs after
  43818. startIndex will be used
  43819. @param deltaX the amount to add to their x-positions
  43820. @param deltaY the amount to add to their y-positions
  43821. */
  43822. void moveRangeOfGlyphs (int startIndex, int numGlyphs,
  43823. float deltaX, float deltaY);
  43824. /** Removes a set of glyphs from the arrangement.
  43825. @param startIndex the first glyph to remove
  43826. @param numGlyphs the number of glyphs to remove; if this is < 0, all glyphs after
  43827. startIndex will be deleted
  43828. */
  43829. void removeRangeOfGlyphs (int startIndex, int numGlyphs);
  43830. /** Expands or compresses a set of glyphs horizontally.
  43831. @param startIndex the first glyph to transform
  43832. @param numGlyphs the number of glyphs to stretch; if this is < 0, all glyphs after
  43833. startIndex will be used
  43834. @param horizontalScaleFactor how much to scale their horizontal width by
  43835. */
  43836. void stretchRangeOfGlyphs (int startIndex, int numGlyphs,
  43837. float horizontalScaleFactor);
  43838. /** Justifies a set of glyphs within a given space.
  43839. This moves the glyphs as a block so that the whole thing is located within the
  43840. given rectangle with the specified layout.
  43841. If the Justification::horizontallyJustified flag is specified, each line will
  43842. be stretched out to fill the specified width.
  43843. */
  43844. void justifyGlyphs (int startIndex, int numGlyphs,
  43845. float x, float y, float width, float height,
  43846. const Justification& justification);
  43847. private:
  43848. OwnedArray <PositionedGlyph> glyphs;
  43849. int insertEllipsis (const Font&, float maxXPos, int startIndex, int endIndex);
  43850. int fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font&,
  43851. const Justification&, float minimumHorizontalScale);
  43852. void spreadOutLine (int start, int numGlyphs, float targetWidth);
  43853. JUCE_LEAK_DETECTOR (GlyphArrangement);
  43854. };
  43855. #endif // __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  43856. /*** End of inlined file: juce_GlyphArrangement.h ***/
  43857. /*** Start of inlined file: juce_AlertWindow.h ***/
  43858. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  43859. #define __JUCE_ALERTWINDOW_JUCEHEADER__
  43860. /*** Start of inlined file: juce_TextLayout.h ***/
  43861. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  43862. #define __JUCE_TEXTLAYOUT_JUCEHEADER__
  43863. class Graphics;
  43864. /**
  43865. A laid-out arrangement of text.
  43866. You can add text in different fonts to a TextLayout object, then call its
  43867. layout() method to word-wrap it into lines. The layout can then be drawn
  43868. using a graphics context.
  43869. It's handy if you've got a message to display, because you can format it,
  43870. measure the extent of the layout, and then create a suitably-sized window
  43871. to show it in.
  43872. @see Font, Graphics::drawFittedText, GlyphArrangement
  43873. */
  43874. class JUCE_API TextLayout
  43875. {
  43876. public:
  43877. /** Creates an empty text layout.
  43878. Text can then be appended using the appendText() method.
  43879. */
  43880. TextLayout();
  43881. /** Creates a copy of another layout object. */
  43882. TextLayout (const TextLayout& other);
  43883. /** Creates a text layout from an initial string and font. */
  43884. TextLayout (const String& text, const Font& font);
  43885. /** Destructor. */
  43886. ~TextLayout();
  43887. /** Copies another layout onto this one. */
  43888. TextLayout& operator= (const TextLayout& layoutToCopy);
  43889. /** Clears the layout, removing all its text. */
  43890. void clear();
  43891. /** Adds a string to the end of the arrangement.
  43892. The string will be broken onto new lines wherever it contains
  43893. carriage-returns or linefeeds. After adding it, you can call layout()
  43894. to wrap long lines into a paragraph and justify it.
  43895. */
  43896. void appendText (const String& textToAppend,
  43897. const Font& fontToUse);
  43898. /** Replaces all the text with a new string.
  43899. This is equivalent to calling clear() followed by appendText().
  43900. */
  43901. void setText (const String& newText,
  43902. const Font& fontToUse);
  43903. /** Returns true if the layout has not had any text added yet. */
  43904. bool isEmpty() const;
  43905. /** Breaks the text up to form a paragraph with the given width.
  43906. @param maximumWidth any text wider than this will be split
  43907. across multiple lines
  43908. @param justification how the lines are to be laid-out horizontally
  43909. @param attemptToBalanceLineLengths if true, it will try to split the lines at a
  43910. width that keeps all the lines of text at a
  43911. similar length - this is good when you're displaying
  43912. a short message and don't want it to get split
  43913. onto two lines with only a couple of words on
  43914. the second line, which looks untidy.
  43915. */
  43916. void layout (int maximumWidth,
  43917. const Justification& justification,
  43918. bool attemptToBalanceLineLengths);
  43919. /** Returns the overall width of the entire text layout. */
  43920. int getWidth() const;
  43921. /** Returns the overall height of the entire text layout. */
  43922. int getHeight() const;
  43923. /** Returns the total number of lines of text. */
  43924. int getNumLines() const { return totalLines; }
  43925. /** Returns the width of a particular line of text.
  43926. @param lineNumber the line, from 0 to (getNumLines() - 1)
  43927. */
  43928. int getLineWidth (int lineNumber) const;
  43929. /** Renders the text at a specified position using a graphics context.
  43930. */
  43931. void draw (Graphics& g, int topLeftX, int topLeftY) const;
  43932. /** Renders the text within a specified rectangle using a graphics context.
  43933. The justification flags dictate how the block of text should be positioned
  43934. within the rectangle.
  43935. */
  43936. void drawWithin (Graphics& g,
  43937. int x, int y, int w, int h,
  43938. const Justification& layoutFlags) const;
  43939. private:
  43940. class Token;
  43941. friend class OwnedArray <Token>;
  43942. OwnedArray <Token> tokens;
  43943. int totalLines;
  43944. JUCE_LEAK_DETECTOR (TextLayout);
  43945. };
  43946. #endif // __JUCE_TEXTLAYOUT_JUCEHEADER__
  43947. /*** End of inlined file: juce_TextLayout.h ***/
  43948. /** A window that displays a message and has buttons for the user to react to it.
  43949. For simple dialog boxes with just a couple of buttons on them, there are
  43950. some static methods for running these.
  43951. For more complex dialogs, an AlertWindow can be created, then it can have some
  43952. buttons and components added to it, and its runModalLoop() method is then used to
  43953. show it. The value returned by runModalLoop() shows which button the
  43954. user pressed to dismiss the box.
  43955. @see ThreadWithProgressWindow
  43956. */
  43957. class JUCE_API AlertWindow : public TopLevelWindow,
  43958. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  43959. {
  43960. public:
  43961. /** The type of icon to show in the dialog box. */
  43962. enum AlertIconType
  43963. {
  43964. NoIcon, /**< No icon will be shown on the dialog box. */
  43965. QuestionIcon, /**< A question-mark icon, for dialog boxes that need the
  43966. user to answer a question. */
  43967. WarningIcon, /**< An exclamation mark to indicate that the dialog is a
  43968. warning about something and shouldn't be ignored. */
  43969. InfoIcon /**< An icon that indicates that the dialog box is just
  43970. giving the user some information, which doesn't require
  43971. a response from them. */
  43972. };
  43973. /** Creates an AlertWindow.
  43974. @param title the headline to show at the top of the dialog box
  43975. @param message a longer, more descriptive message to show underneath the
  43976. headline
  43977. @param iconType the type of icon to display
  43978. @param associatedComponent if this is non-null, it specifies the component that the
  43979. alert window should be associated with. Depending on the look
  43980. and feel, this might be used for positioning of the alert window.
  43981. */
  43982. AlertWindow (const String& title,
  43983. const String& message,
  43984. AlertIconType iconType,
  43985. Component* associatedComponent = nullptr);
  43986. /** Destroys the AlertWindow */
  43987. ~AlertWindow();
  43988. /** Returns the type of alert icon that was specified when the window
  43989. was created. */
  43990. AlertIconType getAlertType() const noexcept { return alertIconType; }
  43991. /** Changes the dialog box's message.
  43992. This will also resize the window to fit the new message if required.
  43993. */
  43994. void setMessage (const String& message);
  43995. /** Adds a button to the window.
  43996. @param name the text to show on the button
  43997. @param returnValue the value that should be returned from runModalLoop()
  43998. if this is the button that the user presses.
  43999. @param shortcutKey1 an optional key that can be pressed to trigger this button
  44000. @param shortcutKey2 a second optional key that can be pressed to trigger this button
  44001. */
  44002. void addButton (const String& name,
  44003. int returnValue,
  44004. const KeyPress& shortcutKey1 = KeyPress(),
  44005. const KeyPress& shortcutKey2 = KeyPress());
  44006. /** Returns the number of buttons that the window currently has. */
  44007. int getNumButtons() const;
  44008. /** Invokes a click of one of the buttons. */
  44009. void triggerButtonClick (const String& buttonName);
  44010. /** Adds a textbox to the window for entering strings.
  44011. @param name an internal name for the text-box. This is the name to pass to
  44012. the getTextEditorContents() method to find out what the
  44013. user typed-in.
  44014. @param initialContents a string to show in the text box when it's first shown
  44015. @param onScreenLabel if this is non-empty, it will be displayed next to the
  44016. text-box to label it.
  44017. @param isPasswordBox if true, the text editor will display asterisks instead of
  44018. the actual text
  44019. @see getTextEditorContents
  44020. */
  44021. void addTextEditor (const String& name,
  44022. const String& initialContents,
  44023. const String& onScreenLabel = String::empty,
  44024. bool isPasswordBox = false);
  44025. /** Returns the contents of a named textbox.
  44026. After showing an AlertWindow that contains a text editor, this can be
  44027. used to find out what the user has typed into it.
  44028. @param nameOfTextEditor the name of the text box that you're interested in
  44029. @see addTextEditor
  44030. */
  44031. String getTextEditorContents (const String& nameOfTextEditor) const;
  44032. /** Returns a pointer to a textbox that was added with addTextEditor(). */
  44033. TextEditor* getTextEditor (const String& nameOfTextEditor) const;
  44034. /** Adds a drop-down list of choices to the box.
  44035. After the box has been shown, the getComboBoxComponent() method can
  44036. be used to find out which item the user picked.
  44037. @param name the label to use for the drop-down list
  44038. @param items the list of items to show in it
  44039. @param onScreenLabel if this is non-empty, it will be displayed next to the
  44040. combo-box to label it.
  44041. @see getComboBoxComponent
  44042. */
  44043. void addComboBox (const String& name,
  44044. const StringArray& items,
  44045. const String& onScreenLabel = String::empty);
  44046. /** Returns a drop-down list that was added to the AlertWindow.
  44047. @param nameOfList the name that was passed into the addComboBox() method
  44048. when creating the drop-down
  44049. @returns the ComboBox component, or 0 if none was found for the given name.
  44050. */
  44051. ComboBox* getComboBoxComponent (const String& nameOfList) const;
  44052. /** Adds a block of text.
  44053. This is handy for adding a multi-line note next to a textbox or combo-box,
  44054. to provide more details about what's going on.
  44055. */
  44056. void addTextBlock (const String& text);
  44057. /** Adds a progress-bar to the window.
  44058. @param progressValue a variable that will be repeatedly checked while the
  44059. dialog box is visible, to see how far the process has
  44060. got. The value should be in the range 0 to 1.0
  44061. */
  44062. void addProgressBarComponent (double& progressValue);
  44063. /** Adds a user-defined component to the dialog box.
  44064. @param component the component to add - its size should be set up correctly
  44065. before it is passed in. The caller is responsible for deleting
  44066. the component later on - the AlertWindow won't delete it.
  44067. */
  44068. void addCustomComponent (Component* component);
  44069. /** Returns the number of custom components in the dialog box.
  44070. @see getCustomComponent, addCustomComponent
  44071. */
  44072. int getNumCustomComponents() const;
  44073. /** Returns one of the custom components in the dialog box.
  44074. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  44075. will return 0
  44076. @see getNumCustomComponents, addCustomComponent
  44077. */
  44078. Component* getCustomComponent (int index) const;
  44079. /** Removes one of the custom components in the dialog box.
  44080. Note that this won't delete it, it just removes the component from the window
  44081. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  44082. will return 0
  44083. @returns the component that was removed (or null)
  44084. @see getNumCustomComponents, addCustomComponent
  44085. */
  44086. Component* removeCustomComponent (int index);
  44087. /** Returns true if the window contains any components other than just buttons.*/
  44088. bool containsAnyExtraComponents() const;
  44089. // easy-to-use message box functions:
  44090. /** Shows a dialog box that just has a message and a single button to get rid of it.
  44091. If the callback parameter is null, the box is shown modally, and the method will
  44092. block until the user has clicked the button (or pressed the escape or return keys).
  44093. If the callback parameter is non-null, the box will be displayed and placed into a
  44094. modal state, but this method will return immediately, and the callback will be invoked
  44095. later when the user dismisses the box.
  44096. @param iconType the type of icon to show
  44097. @param title the headline to show at the top of the box
  44098. @param message a longer, more descriptive message to show underneath the
  44099. headline
  44100. @param buttonText the text to show in the button - if this string is empty, the
  44101. default string "ok" (or a localised version) will be used.
  44102. @param associatedComponent if this is non-null, it specifies the component that the
  44103. alert window should be associated with. Depending on the look
  44104. and feel, this might be used for positioning of the alert window.
  44105. */
  44106. #if JUCE_MODAL_LOOPS_PERMITTED
  44107. static void JUCE_CALLTYPE showMessageBox (AlertIconType iconType,
  44108. const String& title,
  44109. const String& message,
  44110. const String& buttonText = String::empty,
  44111. Component* associatedComponent = nullptr);
  44112. #endif
  44113. /** Shows a dialog box that just has a message and a single button to get rid of it.
  44114. If the callback parameter is null, the box is shown modally, and the method will
  44115. block until the user has clicked the button (or pressed the escape or return keys).
  44116. If the callback parameter is non-null, the box will be displayed and placed into a
  44117. modal state, but this method will return immediately, and the callback will be invoked
  44118. later when the user dismisses the box.
  44119. @param iconType the type of icon to show
  44120. @param title the headline to show at the top of the box
  44121. @param message a longer, more descriptive message to show underneath the
  44122. headline
  44123. @param buttonText the text to show in the button - if this string is empty, the
  44124. default string "ok" (or a localised version) will be used.
  44125. @param associatedComponent if this is non-null, it specifies the component that the
  44126. alert window should be associated with. Depending on the look
  44127. and feel, this might be used for positioning of the alert window.
  44128. */
  44129. static void JUCE_CALLTYPE showMessageBoxAsync (AlertIconType iconType,
  44130. const String& title,
  44131. const String& message,
  44132. const String& buttonText = String::empty,
  44133. Component* associatedComponent = nullptr);
  44134. /** Shows a dialog box with two buttons.
  44135. Ideal for ok/cancel or yes/no choices. The return key can also be used
  44136. to trigger the first button, and the escape key for the second button.
  44137. If the callback parameter is null, the box is shown modally, and the method will
  44138. block until the user has clicked the button (or pressed the escape or return keys).
  44139. If the callback parameter is non-null, the box will be displayed and placed into a
  44140. modal state, but this method will return immediately, and the callback will be invoked
  44141. later when the user dismisses the box.
  44142. @param iconType the type of icon to show
  44143. @param title the headline to show at the top of the box
  44144. @param message a longer, more descriptive message to show underneath the
  44145. headline
  44146. @param button1Text the text to show in the first button - if this string is
  44147. empty, the default string "ok" (or a localised version of it)
  44148. will be used.
  44149. @param button2Text the text to show in the second button - if this string is
  44150. empty, the default string "cancel" (or a localised version of it)
  44151. will be used.
  44152. @param associatedComponent if this is non-null, it specifies the component that the
  44153. alert window should be associated with. Depending on the look
  44154. and feel, this might be used for positioning of the alert window.
  44155. @param callback if this is non-null, the menu will be launched asynchronously,
  44156. returning immediately, and the callback will receive a call to its
  44157. modalStateFinished() when the box is dismissed, with its parameter
  44158. being 1 if the ok button was pressed, or 0 for cancel, The callback object
  44159. will be owned and deleted by the system, so make sure that it works
  44160. safely and doesn't keep any references to objects that might be deleted
  44161. before it gets called.
  44162. @returns true if button 1 was clicked, false if it was button 2. If the callback parameter
  44163. is not null, the method always returns false, and the user's choice is delivered
  44164. later by the callback.
  44165. */
  44166. static bool JUCE_CALLTYPE showOkCancelBox (AlertIconType iconType,
  44167. const String& title,
  44168. const String& message,
  44169. #if JUCE_MODAL_LOOPS_PERMITTED
  44170. const String& button1Text = String::empty,
  44171. const String& button2Text = String::empty,
  44172. Component* associatedComponent = nullptr,
  44173. ModalComponentManager::Callback* callback = nullptr);
  44174. #else
  44175. const String& button1Text,
  44176. const String& button2Text,
  44177. Component* associatedComponent,
  44178. ModalComponentManager::Callback* callback);
  44179. #endif
  44180. /** Shows a dialog box with three buttons.
  44181. Ideal for yes/no/cancel boxes.
  44182. The escape key can be used to trigger the third button.
  44183. If the callback parameter is null, the box is shown modally, and the method will
  44184. block until the user has clicked the button (or pressed the escape or return keys).
  44185. If the callback parameter is non-null, the box will be displayed and placed into a
  44186. modal state, but this method will return immediately, and the callback will be invoked
  44187. later when the user dismisses the box.
  44188. @param iconType the type of icon to show
  44189. @param title the headline to show at the top of the box
  44190. @param message a longer, more descriptive message to show underneath the
  44191. headline
  44192. @param button1Text the text to show in the first button - if an empty string, then
  44193. "yes" will be used (or a localised version of it)
  44194. @param button2Text the text to show in the first button - if an empty string, then
  44195. "no" will be used (or a localised version of it)
  44196. @param button3Text the text to show in the first button - if an empty string, then
  44197. "cancel" will be used (or a localised version of it)
  44198. @param associatedComponent if this is non-null, it specifies the component that the
  44199. alert window should be associated with. Depending on the look
  44200. and feel, this might be used for positioning of the alert window.
  44201. @param callback if this is non-null, the menu will be launched asynchronously,
  44202. returning immediately, and the callback will receive a call to its
  44203. modalStateFinished() when the box is dismissed, with its parameter
  44204. being 1 if the "yes" button was pressed, 2 for the "no" button, or 0
  44205. if it was cancelled, The callback object will be owned and deleted by the
  44206. system, so make sure that it works safely and doesn't keep any references
  44207. to objects that might be deleted before it gets called.
  44208. @returns If the callback parameter has been set, this returns 0. Otherwise, it
  44209. returns one of the following values:
  44210. - 0 if the third button was pressed (normally used for 'cancel')
  44211. - 1 if the first button was pressed (normally used for 'yes')
  44212. - 2 if the middle button was pressed (normally used for 'no')
  44213. */
  44214. static int JUCE_CALLTYPE showYesNoCancelBox (AlertIconType iconType,
  44215. const String& title,
  44216. const String& message,
  44217. #if JUCE_MODAL_LOOPS_PERMITTED
  44218. const String& button1Text = String::empty,
  44219. const String& button2Text = String::empty,
  44220. const String& button3Text = String::empty,
  44221. Component* associatedComponent = nullptr,
  44222. ModalComponentManager::Callback* callback = nullptr);
  44223. #else
  44224. const String& button1Text,
  44225. const String& button2Text,
  44226. const String& button3Text,
  44227. Component* associatedComponent,
  44228. ModalComponentManager::Callback* callback);
  44229. #endif
  44230. /** Shows an operating-system native dialog box.
  44231. @param title the title to use at the top
  44232. @param bodyText the longer message to show
  44233. @param isOkCancel if true, this will show an ok/cancel box, if false,
  44234. it'll show a box with just an ok button
  44235. @returns true if the ok button was pressed, false if they pressed cancel.
  44236. */
  44237. #if JUCE_MODAL_LOOPS_PERMITTED
  44238. static bool JUCE_CALLTYPE showNativeDialogBox (const String& title,
  44239. const String& bodyText,
  44240. bool isOkCancel);
  44241. #endif
  44242. /** A set of colour IDs to use to change the colour of various aspects of the alert box.
  44243. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44244. methods.
  44245. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  44246. */
  44247. enum ColourIds
  44248. {
  44249. backgroundColourId = 0x1001800, /**< The background colour for the window. */
  44250. textColourId = 0x1001810, /**< The colour for the text. */
  44251. outlineColourId = 0x1001820 /**< An optional colour to use to draw a border around the window. */
  44252. };
  44253. protected:
  44254. /** @internal */
  44255. void paint (Graphics& g);
  44256. /** @internal */
  44257. void mouseDown (const MouseEvent& e);
  44258. /** @internal */
  44259. void mouseDrag (const MouseEvent& e);
  44260. /** @internal */
  44261. bool keyPressed (const KeyPress& key);
  44262. /** @internal */
  44263. void buttonClicked (Button* button);
  44264. /** @internal */
  44265. void lookAndFeelChanged();
  44266. /** @internal */
  44267. void userTriedToCloseWindow();
  44268. /** @internal */
  44269. int getDesktopWindowStyleFlags() const;
  44270. private:
  44271. String text;
  44272. TextLayout textLayout;
  44273. AlertIconType alertIconType;
  44274. ComponentBoundsConstrainer constrainer;
  44275. ComponentDragger dragger;
  44276. Rectangle<int> textArea;
  44277. OwnedArray<TextButton> buttons;
  44278. OwnedArray<TextEditor> textBoxes;
  44279. OwnedArray<ComboBox> comboBoxes;
  44280. OwnedArray<ProgressBar> progressBars;
  44281. Array<Component*> customComps;
  44282. OwnedArray<Component> textBlocks;
  44283. Array<Component*> allComps;
  44284. StringArray textboxNames, comboBoxNames;
  44285. Font font;
  44286. Component* associatedComponent;
  44287. void updateLayout (bool onlyIncreaseSize);
  44288. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AlertWindow);
  44289. };
  44290. #endif // __JUCE_ALERTWINDOW_JUCEHEADER__
  44291. /*** End of inlined file: juce_AlertWindow.h ***/
  44292. /**
  44293. A file open/save dialog box.
  44294. This is a Juce-based file dialog box; to use a native file chooser, see the
  44295. FileChooser class.
  44296. To use one of these, create it and call its show() method. e.g.
  44297. @code
  44298. {
  44299. WildcardFileFilter wildcardFilter ("*.foo", String::empty, "Foo files");
  44300. FileBrowserComponent browser (FileBrowserComponent::canSelectFiles,
  44301. File::nonexistent,
  44302. &wildcardFilter,
  44303. nullptr);
  44304. FileChooserDialogBox dialogBox ("Open some kind of file",
  44305. "Please choose some kind of file that you want to open...",
  44306. browser,
  44307. false,
  44308. Colours::lightgrey);
  44309. if (dialogBox.show())
  44310. {
  44311. File selectedFile = browser.getSelectedFile (0);
  44312. ...etc..
  44313. }
  44314. }
  44315. @endcode
  44316. @see FileChooser
  44317. */
  44318. class JUCE_API FileChooserDialogBox : public ResizableWindow,
  44319. public ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  44320. public FileBrowserListener
  44321. {
  44322. public:
  44323. /** Creates a file chooser box.
  44324. @param title the main title to show at the top of the box
  44325. @param instructions an optional longer piece of text to show below the title in
  44326. a smaller font, describing in more detail what's required.
  44327. @param browserComponent a FileBrowserComponent that will be shown inside this dialog
  44328. box. Make sure you delete this after (but not before!) the
  44329. dialog box has been deleted.
  44330. @param warnAboutOverwritingExistingFiles if true, then the user will be asked to confirm
  44331. if they try to select a file that already exists. (This
  44332. flag is only used when saving files)
  44333. @param backgroundColour the background colour for the top level window
  44334. @see FileBrowserComponent, FilePreviewComponent
  44335. */
  44336. FileChooserDialogBox (const String& title,
  44337. const String& instructions,
  44338. FileBrowserComponent& browserComponent,
  44339. bool warnAboutOverwritingExistingFiles,
  44340. const Colour& backgroundColour);
  44341. /** Destructor. */
  44342. ~FileChooserDialogBox();
  44343. #if JUCE_MODAL_LOOPS_PERMITTED
  44344. /** Displays and runs the dialog box modally.
  44345. This will show the box with the specified size, returning true if the user
  44346. pressed 'ok', or false if they cancelled.
  44347. Leave the width or height as 0 to use the default size
  44348. */
  44349. bool show (int width = 0, int height = 0);
  44350. /** Displays and runs the dialog box modally.
  44351. This will show the box with the specified size at the specified location,
  44352. returning true if the user pressed 'ok', or false if they cancelled.
  44353. Leave the width or height as 0 to use the default size.
  44354. */
  44355. bool showAt (int x, int y, int width, int height);
  44356. #endif
  44357. /** Sets the size of this dialog box to its default and positions it either in the
  44358. centre of the screen, or centred around a component that is provided.
  44359. */
  44360. void centreWithDefaultSize (Component* componentToCentreAround = 0);
  44361. /** A set of colour IDs to use to change the colour of various aspects of the box.
  44362. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44363. methods.
  44364. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  44365. */
  44366. enum ColourIds
  44367. {
  44368. titleTextColourId = 0x1000850, /**< The colour to use to draw the box's title. */
  44369. };
  44370. /** @internal */
  44371. void buttonClicked (Button* button);
  44372. /** @internal */
  44373. void closeButtonPressed();
  44374. /** @internal */
  44375. void selectionChanged();
  44376. /** @internal */
  44377. void fileClicked (const File& file, const MouseEvent& e);
  44378. /** @internal */
  44379. void fileDoubleClicked (const File& file);
  44380. private:
  44381. class ContentComponent;
  44382. ContentComponent* content;
  44383. const bool warnAboutOverwritingExistingFiles;
  44384. void okButtonPressed();
  44385. void createNewFolder();
  44386. void createNewFolderConfirmed (const String& name);
  44387. static void okToOverwriteFileCallback (int result, FileChooserDialogBox*);
  44388. static void createNewFolderCallback (int result, FileChooserDialogBox*, Component::SafePointer<AlertWindow>);
  44389. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileChooserDialogBox);
  44390. };
  44391. #endif // __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  44392. /*** End of inlined file: juce_FileChooserDialogBox.h ***/
  44393. #endif
  44394. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  44395. #endif
  44396. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  44397. /*** Start of inlined file: juce_FileListComponent.h ***/
  44398. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  44399. #define __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  44400. /**
  44401. A component that displays the files in a directory as a listbox.
  44402. This implements the DirectoryContentsDisplayComponent base class so that
  44403. it can be used in a FileBrowserComponent.
  44404. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  44405. class and the FileBrowserListener class.
  44406. @see DirectoryContentsList, FileTreeComponent
  44407. */
  44408. class JUCE_API FileListComponent : public ListBox,
  44409. public DirectoryContentsDisplayComponent,
  44410. private ListBoxModel,
  44411. private ChangeListener
  44412. {
  44413. public:
  44414. /** Creates a listbox to show the contents of a specified directory.
  44415. */
  44416. FileListComponent (DirectoryContentsList& listToShow);
  44417. /** Destructor. */
  44418. ~FileListComponent();
  44419. /** Returns the number of files the user has got selected.
  44420. @see getSelectedFile
  44421. */
  44422. int getNumSelectedFiles() const;
  44423. /** Returns one of the files that the user has currently selected.
  44424. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  44425. @see getNumSelectedFiles
  44426. */
  44427. const File getSelectedFile (int index = 0) const;
  44428. /** Deselects any files that are currently selected. */
  44429. void deselectAllFiles();
  44430. /** Scrolls to the top of the list. */
  44431. void scrollToTop();
  44432. /** @internal */
  44433. void changeListenerCallback (ChangeBroadcaster*);
  44434. /** @internal */
  44435. int getNumRows();
  44436. /** @internal */
  44437. void paintListBoxItem (int, Graphics&, int, int, bool);
  44438. /** @internal */
  44439. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  44440. /** @internal */
  44441. void selectedRowsChanged (int lastRowSelected);
  44442. /** @internal */
  44443. void deleteKeyPressed (int currentSelectedRow);
  44444. /** @internal */
  44445. void returnKeyPressed (int currentSelectedRow);
  44446. private:
  44447. File lastDirectory;
  44448. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListComponent);
  44449. };
  44450. #endif // __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  44451. /*** End of inlined file: juce_FileListComponent.h ***/
  44452. #endif
  44453. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  44454. /*** Start of inlined file: juce_FilenameComponent.h ***/
  44455. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  44456. #define __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  44457. class FilenameComponent;
  44458. /**
  44459. Listens for events happening to a FilenameComponent.
  44460. Use FilenameComponent::addListener() and FilenameComponent::removeListener() to
  44461. register one of these objects for event callbacks when the filename is changed.
  44462. @see FilenameComponent
  44463. */
  44464. class JUCE_API FilenameComponentListener
  44465. {
  44466. public:
  44467. /** Destructor. */
  44468. virtual ~FilenameComponentListener() {}
  44469. /** This method is called after the FilenameComponent's file has been changed. */
  44470. virtual void filenameComponentChanged (FilenameComponent* fileComponentThatHasChanged) = 0;
  44471. };
  44472. /**
  44473. Shows a filename as an editable text box, with a 'browse' button and a
  44474. drop-down list for recently selected files.
  44475. A handy component for dialogue boxes where you want the user to be able to
  44476. select a file or directory.
  44477. Attach an FilenameComponentListener using the addListener() method, and it will
  44478. get called each time the user changes the filename, either by browsing for a file
  44479. and clicking 'ok', or by typing a new filename into the box and pressing return.
  44480. @see FileChooser, ComboBox
  44481. */
  44482. class JUCE_API FilenameComponent : public Component,
  44483. public SettableTooltipClient,
  44484. public FileDragAndDropTarget,
  44485. private AsyncUpdater,
  44486. private ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  44487. private ComboBoxListener
  44488. {
  44489. public:
  44490. /** Creates a FilenameComponent.
  44491. @param name the name for this component.
  44492. @param currentFile the file to initially show in the box
  44493. @param canEditFilename if true, the user can manually edit the filename; if false,
  44494. they can only change it by browsing for a new file
  44495. @param isDirectory if true, the file will be treated as a directory, and
  44496. an appropriate directory browser used
  44497. @param isForSaving if true, the file browser will allow non-existent files to
  44498. be picked, as the file is assumed to be used for saving rather
  44499. than loading
  44500. @param fileBrowserWildcard a wildcard pattern to use in the file browser - e.g. "*.txt;*.foo".
  44501. If an empty string is passed in, then the pattern is assumed to be "*"
  44502. @param enforcedSuffix if this is non-empty, it is treated as a suffix that will be added
  44503. to any filenames that are entered or chosen
  44504. @param textWhenNothingSelected the message to display in the box before any filename is entered. (This
  44505. will only appear if the initial file isn't valid)
  44506. */
  44507. FilenameComponent (const String& name,
  44508. const File& currentFile,
  44509. bool canEditFilename,
  44510. bool isDirectory,
  44511. bool isForSaving,
  44512. const String& fileBrowserWildcard,
  44513. const String& enforcedSuffix,
  44514. const String& textWhenNothingSelected);
  44515. /** Destructor. */
  44516. ~FilenameComponent();
  44517. /** Returns the currently displayed filename. */
  44518. File getCurrentFile() const;
  44519. /** Changes the current filename.
  44520. If addToRecentlyUsedList is true, the filename will also be added to the
  44521. drop-down list of recent files.
  44522. If sendChangeNotification is false, then the listeners won't be told of the
  44523. change.
  44524. */
  44525. void setCurrentFile (File newFile,
  44526. bool addToRecentlyUsedList,
  44527. bool sendChangeNotification = true);
  44528. /** Changes whether the use can type into the filename box.
  44529. */
  44530. void setFilenameIsEditable (bool shouldBeEditable);
  44531. /** Sets a file or directory to be the default starting point for the browser to show.
  44532. This is only used if the current file hasn't been set.
  44533. */
  44534. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  44535. /** Returns all the entries on the recent files list.
  44536. This can be used in conjunction with setRecentlyUsedFilenames() for saving the
  44537. state of this list.
  44538. @see setRecentlyUsedFilenames
  44539. */
  44540. StringArray getRecentlyUsedFilenames() const;
  44541. /** Sets all the entries on the recent files list.
  44542. This can be used in conjunction with getRecentlyUsedFilenames() for saving the
  44543. state of this list.
  44544. @see getRecentlyUsedFilenames, addRecentlyUsedFile
  44545. */
  44546. void setRecentlyUsedFilenames (const StringArray& filenames);
  44547. /** Adds an entry to the recently-used files dropdown list.
  44548. If the file is already in the list, it will be moved to the top. A limit
  44549. is also placed on the number of items that are kept in the list.
  44550. @see getRecentlyUsedFilenames, setRecentlyUsedFilenames, setMaxNumberOfRecentFiles
  44551. */
  44552. void addRecentlyUsedFile (const File& file);
  44553. /** Changes the limit for the number of files that will be stored in the recent-file list.
  44554. */
  44555. void setMaxNumberOfRecentFiles (int newMaximum);
  44556. /** Changes the text shown on the 'browse' button.
  44557. By default this button just says "..." but you can change it. The button itself
  44558. can be changed using the look-and-feel classes, so it might not actually have any
  44559. text on it.
  44560. */
  44561. void setBrowseButtonText (const String& browseButtonText);
  44562. /** Adds a listener that will be called when the selected file is changed. */
  44563. void addListener (FilenameComponentListener* listener);
  44564. /** Removes a previously-registered listener. */
  44565. void removeListener (FilenameComponentListener* listener);
  44566. /** Gives the component a tooltip. */
  44567. void setTooltip (const String& newTooltip);
  44568. /** @internal */
  44569. void paintOverChildren (Graphics& g);
  44570. /** @internal */
  44571. void resized();
  44572. /** @internal */
  44573. void lookAndFeelChanged();
  44574. /** @internal */
  44575. bool isInterestedInFileDrag (const StringArray& files);
  44576. /** @internal */
  44577. void filesDropped (const StringArray& files, int, int);
  44578. /** @internal */
  44579. void fileDragEnter (const StringArray& files, int, int);
  44580. /** @internal */
  44581. void fileDragExit (const StringArray& files);
  44582. private:
  44583. ComboBox filenameBox;
  44584. String lastFilename;
  44585. ScopedPointer<Button> browseButton;
  44586. int maxRecentFiles;
  44587. bool isDir, isSaving, isFileDragOver;
  44588. String wildcard, enforcedSuffix, browseButtonText;
  44589. ListenerList <FilenameComponentListener> listeners;
  44590. File defaultBrowseFile;
  44591. void comboBoxChanged (ComboBox*);
  44592. void buttonClicked (Button* button);
  44593. void handleAsyncUpdate();
  44594. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FilenameComponent);
  44595. };
  44596. #endif // __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  44597. /*** End of inlined file: juce_FilenameComponent.h ***/
  44598. #endif
  44599. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  44600. #endif
  44601. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  44602. /*** Start of inlined file: juce_FileSearchPathListComponent.h ***/
  44603. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  44604. #define __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  44605. /**
  44606. Shows a set of file paths in a list, allowing them to be added, removed or
  44607. re-ordered.
  44608. @see FileSearchPath
  44609. */
  44610. class JUCE_API FileSearchPathListComponent : public Component,
  44611. public SettableTooltipClient,
  44612. public FileDragAndDropTarget,
  44613. private ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  44614. private ListBoxModel
  44615. {
  44616. public:
  44617. /** Creates an empty FileSearchPathListComponent. */
  44618. FileSearchPathListComponent();
  44619. /** Destructor. */
  44620. ~FileSearchPathListComponent();
  44621. /** Returns the path as it is currently shown. */
  44622. const FileSearchPath& getPath() const noexcept { return path; }
  44623. /** Changes the current path. */
  44624. void setPath (const FileSearchPath& newPath);
  44625. /** Sets a file or directory to be the default starting point for the browser to show.
  44626. This is only used if the current file hasn't been set.
  44627. */
  44628. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  44629. /** A set of colour IDs to use to change the colour of various aspects of the label.
  44630. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44631. methods.
  44632. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  44633. */
  44634. enum ColourIds
  44635. {
  44636. backgroundColourId = 0x1004100, /**< The background colour to fill the component with.
  44637. Make this transparent if you don't want the background to be filled. */
  44638. };
  44639. /** @internal */
  44640. int getNumRows();
  44641. /** @internal */
  44642. void paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected);
  44643. /** @internal */
  44644. void deleteKeyPressed (int lastRowSelected);
  44645. /** @internal */
  44646. void returnKeyPressed (int lastRowSelected);
  44647. /** @internal */
  44648. void listBoxItemDoubleClicked (int row, const MouseEvent&);
  44649. /** @internal */
  44650. void selectedRowsChanged (int lastRowSelected);
  44651. /** @internal */
  44652. void resized();
  44653. /** @internal */
  44654. void paint (Graphics& g);
  44655. /** @internal */
  44656. bool isInterestedInFileDrag (const StringArray& files);
  44657. /** @internal */
  44658. void filesDropped (const StringArray& files, int, int);
  44659. /** @internal */
  44660. void buttonClicked (Button* button);
  44661. private:
  44662. FileSearchPath path;
  44663. File defaultBrowseTarget;
  44664. ListBox listBox;
  44665. TextButton addButton, removeButton, changeButton;
  44666. DrawableButton upButton, downButton;
  44667. void changed();
  44668. void updateButtons();
  44669. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileSearchPathListComponent);
  44670. };
  44671. #endif // __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  44672. /*** End of inlined file: juce_FileSearchPathListComponent.h ***/
  44673. #endif
  44674. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  44675. /*** Start of inlined file: juce_FileTreeComponent.h ***/
  44676. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  44677. #define __JUCE_FILETREECOMPONENT_JUCEHEADER__
  44678. /**
  44679. A component that displays the files in a directory as a treeview.
  44680. This implements the DirectoryContentsDisplayComponent base class so that
  44681. it can be used in a FileBrowserComponent.
  44682. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  44683. class and the FileBrowserListener class.
  44684. @see DirectoryContentsList, FileListComponent
  44685. */
  44686. class JUCE_API FileTreeComponent : public TreeView,
  44687. public DirectoryContentsDisplayComponent
  44688. {
  44689. public:
  44690. /** Creates a listbox to show the contents of a specified directory.
  44691. */
  44692. FileTreeComponent (DirectoryContentsList& listToShow);
  44693. /** Destructor. */
  44694. ~FileTreeComponent();
  44695. /** Returns the number of files the user has got selected.
  44696. @see getSelectedFile
  44697. */
  44698. int getNumSelectedFiles() const { return TreeView::getNumSelectedItems(); }
  44699. /** Returns one of the files that the user has currently selected.
  44700. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  44701. @see getNumSelectedFiles
  44702. */
  44703. const File getSelectedFile (int index = 0) const;
  44704. /** Deselects any files that are currently selected. */
  44705. void deselectAllFiles();
  44706. /** Scrolls the list to the top. */
  44707. void scrollToTop();
  44708. /** Setting a name for this allows tree items to be dragged.
  44709. The string that you pass in here will be returned by the getDragSourceDescription()
  44710. of the items in the tree. For more info, see TreeViewItem::getDragSourceDescription().
  44711. */
  44712. void setDragAndDropDescription (const String& description);
  44713. /** Returns the last value that was set by setDragAndDropDescription().
  44714. */
  44715. const String& getDragAndDropDescription() const noexcept { return dragAndDropDescription; }
  44716. private:
  44717. String dragAndDropDescription;
  44718. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileTreeComponent);
  44719. };
  44720. #endif // __JUCE_FILETREECOMPONENT_JUCEHEADER__
  44721. /*** End of inlined file: juce_FileTreeComponent.h ***/
  44722. #endif
  44723. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  44724. /*** Start of inlined file: juce_ImagePreviewComponent.h ***/
  44725. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  44726. #define __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  44727. /**
  44728. A simple preview component that shows thumbnails of image files.
  44729. @see FileChooserDialogBox, FilePreviewComponent
  44730. */
  44731. class JUCE_API ImagePreviewComponent : public FilePreviewComponent,
  44732. private Timer
  44733. {
  44734. public:
  44735. /** Creates an ImagePreviewComponent. */
  44736. ImagePreviewComponent();
  44737. /** Destructor. */
  44738. ~ImagePreviewComponent();
  44739. /** @internal */
  44740. void selectedFileChanged (const File& newSelectedFile);
  44741. /** @internal */
  44742. void paint (Graphics& g);
  44743. /** @internal */
  44744. void timerCallback();
  44745. private:
  44746. File fileToLoad;
  44747. Image currentThumbnail;
  44748. String currentDetails;
  44749. void getThumbSize (int& w, int& h) const;
  44750. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImagePreviewComponent);
  44751. };
  44752. #endif // __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  44753. /*** End of inlined file: juce_ImagePreviewComponent.h ***/
  44754. #endif
  44755. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  44756. /*** Start of inlined file: juce_WildcardFileFilter.h ***/
  44757. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  44758. #define __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  44759. /**
  44760. A type of FileFilter that works by wildcard pattern matching.
  44761. This filter only allows files that match one of the specified patterns, but
  44762. allows all directories through.
  44763. @see FileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  44764. */
  44765. class JUCE_API WildcardFileFilter : public FileFilter
  44766. {
  44767. public:
  44768. /**
  44769. Creates a wildcard filter for one or more patterns.
  44770. The wildcardPatterns parameter is a comma or semicolon-delimited set of
  44771. patterns, e.g. "*.wav;*.aiff" would look for files ending in either .wav
  44772. or .aiff.
  44773. Passing an empty string as a pattern will fail to match anything, so by leaving
  44774. either the file or directory pattern parameter empty means you can control
  44775. whether files or directories are found.
  44776. The description is a name to show the user in a list of possible patterns, so
  44777. for the wav/aiff example, your description might be "audio files".
  44778. */
  44779. WildcardFileFilter (const String& fileWildcardPatterns,
  44780. const String& directoryWildcardPatterns,
  44781. const String& description);
  44782. /** Destructor. */
  44783. ~WildcardFileFilter();
  44784. /** Returns true if the filename matches one of the patterns specified. */
  44785. bool isFileSuitable (const File& file) const;
  44786. /** This always returns true. */
  44787. bool isDirectorySuitable (const File& file) const;
  44788. private:
  44789. StringArray fileWildcards, directoryWildcards;
  44790. static void parse (const String& pattern, StringArray& result);
  44791. static bool match (const File& file, const StringArray& wildcards);
  44792. JUCE_LEAK_DETECTOR (WildcardFileFilter);
  44793. };
  44794. #endif // __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  44795. /*** End of inlined file: juce_WildcardFileFilter.h ***/
  44796. #endif
  44797. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  44798. #endif
  44799. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  44800. #endif
  44801. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  44802. #endif
  44803. #ifndef __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  44804. #endif
  44805. #ifndef __JUCE_CARETCOMPONENT_JUCEHEADER__
  44806. #endif
  44807. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  44808. #endif
  44809. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  44810. #endif
  44811. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  44812. /*** Start of inlined file: juce_KeyMappingEditorComponent.h ***/
  44813. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  44814. #define __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  44815. /*** Start of inlined file: juce_KeyPressMappingSet.h ***/
  44816. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  44817. #define __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  44818. /**
  44819. Manages and edits a list of keypresses, which it uses to invoke the appropriate
  44820. command in a ApplicationCommandManager.
  44821. Normally, you won't actually create a KeyPressMappingSet directly, because
  44822. each ApplicationCommandManager contains its own KeyPressMappingSet, so typically
  44823. you'd create yourself an ApplicationCommandManager, and call its
  44824. ApplicationCommandManager::getKeyMappings() method to get a pointer to its
  44825. KeyPressMappingSet.
  44826. For one of these to actually use keypresses, you'll need to add it as a KeyListener
  44827. to the top-level component for which you want to handle keystrokes. So for example:
  44828. @code
  44829. class MyMainWindow : public Component
  44830. {
  44831. ApplicationCommandManager* myCommandManager;
  44832. public:
  44833. MyMainWindow()
  44834. {
  44835. myCommandManager = new ApplicationCommandManager();
  44836. // first, make sure the command manager has registered all the commands that its
  44837. // targets can perform..
  44838. myCommandManager->registerAllCommandsForTarget (myCommandTarget1);
  44839. myCommandManager->registerAllCommandsForTarget (myCommandTarget2);
  44840. // this will use the command manager to initialise the KeyPressMappingSet with
  44841. // the default keypresses that were specified when the targets added their commands
  44842. // to the manager.
  44843. myCommandManager->getKeyMappings()->resetToDefaultMappings();
  44844. // having set up the default key-mappings, you might now want to load the last set
  44845. // of mappings that the user configured.
  44846. myCommandManager->getKeyMappings()->restoreFromXml (lastSavedKeyMappingsXML);
  44847. // Now tell our top-level window to send any keypresses that arrive to the
  44848. // KeyPressMappingSet, which will use them to invoke the appropriate commands.
  44849. addKeyListener (myCommandManager->getKeyMappings());
  44850. }
  44851. ...
  44852. }
  44853. @endcode
  44854. KeyPressMappingSet derives from ChangeBroadcaster so that interested parties can
  44855. register to be told when a command or mapping is added, removed, etc.
  44856. There's also a UI component called KeyMappingEditorComponent that can be used
  44857. to easily edit the key mappings.
  44858. @see Component::addKeyListener(), KeyMappingEditorComponent, ApplicationCommandManager
  44859. */
  44860. class JUCE_API KeyPressMappingSet : public KeyListener,
  44861. public ChangeBroadcaster,
  44862. public FocusChangeListener
  44863. {
  44864. public:
  44865. /** Creates a KeyPressMappingSet for a given command manager.
  44866. Normally, you won't actually create a KeyPressMappingSet directly, because
  44867. each ApplicationCommandManager contains its own KeyPressMappingSet, so the
  44868. best thing to do is to create your ApplicationCommandManager, and use the
  44869. ApplicationCommandManager::getKeyMappings() method to access its mappings.
  44870. When a suitable keypress happens, the manager's invoke() method will be
  44871. used to invoke the appropriate command.
  44872. @see ApplicationCommandManager
  44873. */
  44874. explicit KeyPressMappingSet (ApplicationCommandManager* commandManager);
  44875. /** Creates an copy of a KeyPressMappingSet. */
  44876. KeyPressMappingSet (const KeyPressMappingSet& other);
  44877. /** Destructor. */
  44878. ~KeyPressMappingSet();
  44879. ApplicationCommandManager* getCommandManager() const noexcept { return commandManager; }
  44880. /** Returns a list of keypresses that are assigned to a particular command.
  44881. @param commandID the command's ID
  44882. */
  44883. const Array <KeyPress> getKeyPressesAssignedToCommand (CommandID commandID) const;
  44884. /** Assigns a keypress to a command.
  44885. If the keypress is already assigned to a different command, it will first be
  44886. removed from that command, to avoid it triggering multiple functions.
  44887. @param commandID the ID of the command that you want to add a keypress to. If
  44888. this is 0, the keypress will be removed from anything that it
  44889. was previously assigned to, but not re-assigned
  44890. @param newKeyPress the new key-press
  44891. @param insertIndex if this is less than zero, the key will be appended to the
  44892. end of the list of keypresses; otherwise the new keypress will
  44893. be inserted into the existing list at this index
  44894. */
  44895. void addKeyPress (CommandID commandID,
  44896. const KeyPress& newKeyPress,
  44897. int insertIndex = -1);
  44898. /** Reset all mappings to the defaults, as dictated by the ApplicationCommandManager.
  44899. @see resetToDefaultMapping
  44900. */
  44901. void resetToDefaultMappings();
  44902. /** Resets all key-mappings to the defaults for a particular command.
  44903. @see resetToDefaultMappings
  44904. */
  44905. void resetToDefaultMapping (CommandID commandID);
  44906. /** Removes all keypresses that are assigned to any commands. */
  44907. void clearAllKeyPresses();
  44908. /** Removes all keypresses that are assigned to a particular command. */
  44909. void clearAllKeyPresses (CommandID commandID);
  44910. /** Removes one of the keypresses that are assigned to a command.
  44911. See the getKeyPressesAssignedToCommand() for the list of keypresses to
  44912. which the keyPressIndex refers.
  44913. */
  44914. void removeKeyPress (CommandID commandID, int keyPressIndex);
  44915. /** Removes a keypress from any command that it may be assigned to.
  44916. */
  44917. void removeKeyPress (const KeyPress& keypress);
  44918. /** Returns true if the given command is linked to this key. */
  44919. bool containsMapping (CommandID commandID, const KeyPress& keyPress) const noexcept;
  44920. /** Looks for a command that corresponds to a keypress.
  44921. @returns the UID of the command or 0 if none was found
  44922. */
  44923. CommandID findCommandForKeyPress (const KeyPress& keyPress) const noexcept;
  44924. /** Tries to recreate the mappings from a previously stored state.
  44925. The XML passed in must have been created by the createXml() method.
  44926. If the stored state makes any reference to commands that aren't
  44927. currently available, these will be ignored.
  44928. If the set of mappings being loaded was a set of differences (using createXml (true)),
  44929. then this will call resetToDefaultMappings() and then merge the saved mappings
  44930. on top. If the saved set was created with createXml (false), then this method
  44931. will first clear all existing mappings and load the saved ones as a complete set.
  44932. @returns true if it manages to load the XML correctly
  44933. @see createXml
  44934. */
  44935. bool restoreFromXml (const XmlElement& xmlVersion);
  44936. /** Creates an XML representation of the current mappings.
  44937. This will produce a lump of XML that can be later reloaded using
  44938. restoreFromXml() to recreate the current mapping state.
  44939. The object that is returned must be deleted by the caller.
  44940. @param saveDifferencesFromDefaultSet if this is false, then all keypresses
  44941. will be saved into the XML. If it's true, then the XML will
  44942. only store the differences between the current mappings and
  44943. the default mappings you'd get from calling resetToDefaultMappings().
  44944. The advantage of saving a set of differences from the default is that
  44945. if you change the default mappings (in a new version of your app, for
  44946. example), then these will be merged into a user's saved preferences.
  44947. @see restoreFromXml
  44948. */
  44949. XmlElement* createXml (bool saveDifferencesFromDefaultSet) const;
  44950. /** @internal */
  44951. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  44952. /** @internal */
  44953. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  44954. /** @internal */
  44955. void globalFocusChanged (Component* focusedComponent);
  44956. private:
  44957. ApplicationCommandManager* commandManager;
  44958. struct CommandMapping
  44959. {
  44960. CommandID commandID;
  44961. Array <KeyPress> keypresses;
  44962. bool wantsKeyUpDownCallbacks;
  44963. };
  44964. OwnedArray <CommandMapping> mappings;
  44965. struct KeyPressTime
  44966. {
  44967. KeyPress key;
  44968. uint32 timeWhenPressed;
  44969. };
  44970. OwnedArray <KeyPressTime> keysDown;
  44971. void handleMessage (const Message& message);
  44972. void invokeCommand (const CommandID commandID,
  44973. const KeyPress& keyPress,
  44974. const bool isKeyDown,
  44975. const int millisecsSinceKeyPressed,
  44976. Component* const originatingComponent) const;
  44977. KeyPressMappingSet& operator= (const KeyPressMappingSet&);
  44978. JUCE_LEAK_DETECTOR (KeyPressMappingSet);
  44979. };
  44980. #endif // __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  44981. /*** End of inlined file: juce_KeyPressMappingSet.h ***/
  44982. /**
  44983. A component to allow editing of the keymaps stored by a KeyPressMappingSet
  44984. object.
  44985. @see KeyPressMappingSet
  44986. */
  44987. class JUCE_API KeyMappingEditorComponent : public Component
  44988. {
  44989. public:
  44990. /** Creates a KeyMappingEditorComponent.
  44991. @param mappingSet this is the set of mappings to display and edit. Make sure the
  44992. mappings object is not deleted before this component!
  44993. @param showResetToDefaultButton if true, then at the bottom of the list, the
  44994. component will include a 'reset to defaults' button.
  44995. */
  44996. KeyMappingEditorComponent (KeyPressMappingSet& mappingSet,
  44997. bool showResetToDefaultButton);
  44998. /** Destructor. */
  44999. virtual ~KeyMappingEditorComponent();
  45000. /** Sets up the colours to use for parts of the component.
  45001. @param mainBackground colour to use for most of the background
  45002. @param textColour colour to use for the text
  45003. */
  45004. void setColours (const Colour& mainBackground,
  45005. const Colour& textColour);
  45006. /** Returns the KeyPressMappingSet that this component is acting upon. */
  45007. KeyPressMappingSet& getMappings() const noexcept { return mappings; }
  45008. /** Can be overridden if some commands need to be excluded from the list.
  45009. By default this will use the KeyPressMappingSet's shouldCommandBeVisibleInEditor()
  45010. method to decide what to return, but you can override it to handle special cases.
  45011. */
  45012. virtual bool shouldCommandBeIncluded (CommandID commandID);
  45013. /** Can be overridden to indicate that some commands are shown as read-only.
  45014. By default this will use the KeyPressMappingSet's shouldCommandBeReadOnlyInEditor()
  45015. method to decide what to return, but you can override it to handle special cases.
  45016. */
  45017. virtual bool isCommandReadOnly (CommandID commandID);
  45018. /** This can be overridden to let you change the format of the string used
  45019. to describe a keypress.
  45020. This is handy if you're using non-standard KeyPress objects, e.g. for custom
  45021. keys that are triggered by something else externally. If you override the
  45022. method, be sure to let the base class's method handle keys you're not
  45023. interested in.
  45024. */
  45025. virtual const String getDescriptionForKeyPress (const KeyPress& key);
  45026. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  45027. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  45028. methods.
  45029. To change the colours of the menu that pops up
  45030. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  45031. */
  45032. enum ColourIds
  45033. {
  45034. backgroundColourId = 0x100ad00, /**< The background colour to fill the editor background. */
  45035. textColourId = 0x100ad01, /**< The colour for the text. */
  45036. };
  45037. /** @internal */
  45038. void parentHierarchyChanged();
  45039. /** @internal */
  45040. void resized();
  45041. private:
  45042. KeyPressMappingSet& mappings;
  45043. TreeView tree;
  45044. TextButton resetButton;
  45045. class TopLevelItem;
  45046. class ChangeKeyButton;
  45047. class MappingItem;
  45048. class CategoryItem;
  45049. class ItemComponent;
  45050. friend class TopLevelItem;
  45051. friend class OwnedArray <ChangeKeyButton>;
  45052. friend class ScopedPointer<TopLevelItem>;
  45053. ScopedPointer<TopLevelItem> treeItem;
  45054. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (KeyMappingEditorComponent);
  45055. };
  45056. #endif // __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  45057. /*** End of inlined file: juce_KeyMappingEditorComponent.h ***/
  45058. #endif
  45059. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  45060. #endif
  45061. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  45062. #endif
  45063. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  45064. #endif
  45065. #ifndef __JUCE_TEXTEDITORKEYMAPPER_JUCEHEADER__
  45066. /*** Start of inlined file: juce_TextEditorKeyMapper.h ***/
  45067. #ifndef __JUCE_TEXTEDITORKEYMAPPER_JUCEHEADER__
  45068. #define __JUCE_TEXTEDITORKEYMAPPER_JUCEHEADER__
  45069. /** This class is used to invoke a range of text-editor navigation methods on
  45070. an object, based upon a keypress event.
  45071. It's currently used internally by the TextEditor and CodeEditorComponent.
  45072. */
  45073. template <class CallbackClass>
  45074. struct TextEditorKeyMapper
  45075. {
  45076. /** Checks the keypress and invokes one of a range of navigation functions that
  45077. the target class must implement, based on the key event.
  45078. */
  45079. static bool invokeKeyFunction (CallbackClass& target, const KeyPress& key)
  45080. {
  45081. const bool isShiftDown = key.getModifiers().isShiftDown();
  45082. const bool ctrlOrAltDown = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  45083. if (key == KeyPress (KeyPress::downKey, ModifierKeys::ctrlModifier, 0)
  45084. && target.scrollUp())
  45085. return true;
  45086. if (key == KeyPress (KeyPress::upKey, ModifierKeys::ctrlModifier, 0)
  45087. && target.scrollDown())
  45088. return true;
  45089. #if JUCE_MAC
  45090. if (key.getModifiers().isCommandDown())
  45091. {
  45092. if (key.isKeyCode (KeyPress::upKey))
  45093. return target.moveCaretToTop (isShiftDown);
  45094. if (key.isKeyCode (KeyPress::downKey))
  45095. return target.moveCaretToEnd (isShiftDown);
  45096. if (key.isKeyCode (KeyPress::leftKey))
  45097. return target.moveCaretToStartOfLine (isShiftDown);
  45098. if (key.isKeyCode (KeyPress::rightKey))
  45099. return target.moveCaretToEndOfLine (isShiftDown);
  45100. }
  45101. #endif
  45102. if (key.isKeyCode (KeyPress::upKey))
  45103. return target.moveCaretUp (isShiftDown);
  45104. if (key.isKeyCode (KeyPress::downKey))
  45105. return target.moveCaretDown (isShiftDown);
  45106. if (key.isKeyCode (KeyPress::leftKey))
  45107. return target.moveCaretLeft (ctrlOrAltDown, isShiftDown);
  45108. if (key.isKeyCode (KeyPress::rightKey))
  45109. return target.moveCaretRight (ctrlOrAltDown, isShiftDown);
  45110. if (key.isKeyCode (KeyPress::pageUpKey))
  45111. return target.pageUp (isShiftDown);
  45112. if (key.isKeyCode (KeyPress::pageDownKey))
  45113. return target.pageDown (isShiftDown);
  45114. if (key.isKeyCode (KeyPress::homeKey))
  45115. return ctrlOrAltDown ? target.moveCaretToTop (isShiftDown)
  45116. : target.moveCaretToStartOfLine (isShiftDown);
  45117. if (key.isKeyCode (KeyPress::endKey))
  45118. return ctrlOrAltDown ? target.moveCaretToEnd (isShiftDown)
  45119. : target.moveCaretToEndOfLine (isShiftDown);
  45120. if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  45121. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  45122. return target.copyToClipboard();
  45123. if (key == KeyPress ('x', ModifierKeys::commandModifier, 0)
  45124. || key == KeyPress (KeyPress::deleteKey, ModifierKeys::shiftModifier, 0))
  45125. return target.cutToClipboard();
  45126. if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  45127. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  45128. return target.pasteFromClipboard();
  45129. if (key.isKeyCode (KeyPress::backspaceKey))
  45130. return target.deleteBackwards (ctrlOrAltDown);
  45131. if (key.isKeyCode (KeyPress::deleteKey))
  45132. return target.deleteForwards (ctrlOrAltDown);
  45133. if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  45134. return target.selectAll();
  45135. if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  45136. return target.undo();
  45137. if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  45138. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  45139. return target.redo();
  45140. return false;
  45141. }
  45142. };
  45143. #endif // __JUCE_TEXTEDITORKEYMAPPER_JUCEHEADER__
  45144. /*** End of inlined file: juce_TextEditorKeyMapper.h ***/
  45145. #endif
  45146. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  45147. #endif
  45148. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  45149. #endif
  45150. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  45151. #endif
  45152. #ifndef __JUCE_COMPONENTBUILDER_JUCEHEADER__
  45153. #endif
  45154. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  45155. /*** Start of inlined file: juce_ComponentMovementWatcher.h ***/
  45156. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  45157. #define __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  45158. /** An object that watches for any movement of a component or any of its parent components.
  45159. This makes it easy to check when a component is moved relative to its top-level
  45160. peer window. The normal Component::moved() method is only called when a component
  45161. moves relative to its immediate parent, and sometimes you want to know if any of
  45162. components higher up the tree have moved (which of course will affect the overall
  45163. position of all their sub-components).
  45164. It also includes a callback that lets you know when the top-level peer is changed.
  45165. This class is used by specialised components like OpenGLComponent or QuickTimeComponent
  45166. because they need to keep their custom windows in the right place and respond to
  45167. changes in the peer.
  45168. */
  45169. class JUCE_API ComponentMovementWatcher : public ComponentListener
  45170. {
  45171. public:
  45172. /** Creates a ComponentMovementWatcher to watch a given target component. */
  45173. ComponentMovementWatcher (Component* component);
  45174. /** Destructor. */
  45175. ~ComponentMovementWatcher();
  45176. /** This callback happens when the component that is being watched is moved
  45177. relative to its top-level peer window, or when it is resized. */
  45178. virtual void componentMovedOrResized (bool wasMoved, bool wasResized) = 0;
  45179. /** This callback happens when the component's top-level peer is changed. */
  45180. virtual void componentPeerChanged() = 0;
  45181. /** This callback happens when the component's visibility state changes, possibly due to
  45182. one of its parents being made visible or invisible.
  45183. */
  45184. virtual void componentVisibilityChanged() = 0;
  45185. /** @internal */
  45186. void componentParentHierarchyChanged (Component& component);
  45187. /** @internal */
  45188. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  45189. /** @internal */
  45190. void componentBeingDeleted (Component& component);
  45191. /** @internal */
  45192. void componentVisibilityChanged (Component& component);
  45193. private:
  45194. WeakReference<Component> component;
  45195. uint32 lastPeerID;
  45196. Array <Component*> registeredParentComps;
  45197. bool reentrant, wasShowing;
  45198. Rectangle<int> lastBounds;
  45199. void unregister();
  45200. void registerWithParentComps();
  45201. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentMovementWatcher);
  45202. };
  45203. #endif // __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  45204. /*** End of inlined file: juce_ComponentMovementWatcher.h ***/
  45205. #endif
  45206. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  45207. /*** Start of inlined file: juce_GroupComponent.h ***/
  45208. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  45209. #define __JUCE_GROUPCOMPONENT_JUCEHEADER__
  45210. /**
  45211. A component that draws an outline around itself and has an optional title at
  45212. the top, for drawing an outline around a group of controls.
  45213. */
  45214. class JUCE_API GroupComponent : public Component
  45215. {
  45216. public:
  45217. /** Creates a GroupComponent.
  45218. @param componentName the name to give the component
  45219. @param labelText the text to show at the top of the outline
  45220. */
  45221. GroupComponent (const String& componentName = String::empty,
  45222. const String& labelText = String::empty);
  45223. /** Destructor. */
  45224. ~GroupComponent();
  45225. /** Changes the text that's shown at the top of the component. */
  45226. void setText (const String& newText);
  45227. /** Returns the currently displayed text label. */
  45228. String getText() const;
  45229. /** Sets the positioning of the text label.
  45230. (The default is Justification::left)
  45231. @see getTextLabelPosition
  45232. */
  45233. void setTextLabelPosition (const Justification& justification);
  45234. /** Returns the current text label position.
  45235. @see setTextLabelPosition
  45236. */
  45237. const Justification getTextLabelPosition() const noexcept { return justification; }
  45238. /** A set of colour IDs to use to change the colour of various aspects of the component.
  45239. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  45240. methods.
  45241. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  45242. */
  45243. enum ColourIds
  45244. {
  45245. outlineColourId = 0x1005400, /**< The colour to use for drawing the line around the edge. */
  45246. textColourId = 0x1005410 /**< The colour to use to draw the text label. */
  45247. };
  45248. /** @internal */
  45249. void paint (Graphics& g);
  45250. /** @internal */
  45251. void enablementChanged();
  45252. /** @internal */
  45253. void colourChanged();
  45254. private:
  45255. String text;
  45256. Justification justification;
  45257. JUCE_DECLARE_NON_COPYABLE (GroupComponent);
  45258. };
  45259. #endif // __JUCE_GROUPCOMPONENT_JUCEHEADER__
  45260. /*** End of inlined file: juce_GroupComponent.h ***/
  45261. #endif
  45262. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  45263. /*** Start of inlined file: juce_MultiDocumentPanel.h ***/
  45264. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  45265. #define __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  45266. /*** Start of inlined file: juce_TabbedComponent.h ***/
  45267. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  45268. #define __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  45269. /*** Start of inlined file: juce_TabbedButtonBar.h ***/
  45270. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  45271. #define __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  45272. class TabbedButtonBar;
  45273. /** In a TabbedButtonBar, this component is used for each of the buttons.
  45274. If you want to create a TabbedButtonBar with custom tab components, derive
  45275. your component from this class, and override the TabbedButtonBar::createTabButton()
  45276. method to create it instead of the default one.
  45277. @see TabbedButtonBar
  45278. */
  45279. class JUCE_API TabBarButton : public Button
  45280. {
  45281. public:
  45282. /** Creates the tab button. */
  45283. TabBarButton (const String& name, TabbedButtonBar& ownerBar);
  45284. /** Destructor. */
  45285. ~TabBarButton();
  45286. /** Chooses the best length for the tab, given the specified depth.
  45287. If the tab is horizontal, this should return its width, and the depth
  45288. specifies its height. If it's vertical, it should return the height, and
  45289. the depth is actually its width.
  45290. */
  45291. virtual int getBestTabLength (int depth);
  45292. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  45293. void clicked (const ModifierKeys& mods);
  45294. bool hitTest (int x, int y);
  45295. protected:
  45296. friend class TabbedButtonBar;
  45297. TabbedButtonBar& owner;
  45298. int overlapPixels;
  45299. DropShadowEffect shadow;
  45300. /** Returns an area of the component that's safe to draw in.
  45301. This deals with the orientation of the tabs, which affects which side is
  45302. touching the tabbed box's content component.
  45303. */
  45304. const Rectangle<int> getActiveArea();
  45305. /** Returns this tab's index in its tab bar. */
  45306. int getIndex() const;
  45307. private:
  45308. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabBarButton);
  45309. };
  45310. /**
  45311. A vertical or horizontal bar containing tabs that you can select.
  45312. You can use one of these to generate things like a dialog box that has
  45313. tabbed pages you can flip between. Attach a ChangeListener to the
  45314. button bar to be told when the user changes the page.
  45315. An easier method than doing this is to use a TabbedComponent, which
  45316. contains its own TabbedButtonBar and which takes care of the layout
  45317. and other housekeeping.
  45318. @see TabbedComponent
  45319. */
  45320. class JUCE_API TabbedButtonBar : public Component,
  45321. public ChangeBroadcaster
  45322. {
  45323. public:
  45324. /** The placement of the tab-bar
  45325. @see setOrientation, getOrientation
  45326. */
  45327. enum Orientation
  45328. {
  45329. TabsAtTop,
  45330. TabsAtBottom,
  45331. TabsAtLeft,
  45332. TabsAtRight
  45333. };
  45334. /** Creates a TabbedButtonBar with a given placement.
  45335. You can change the orientation later if you need to.
  45336. */
  45337. TabbedButtonBar (Orientation orientation);
  45338. /** Destructor. */
  45339. ~TabbedButtonBar();
  45340. /** Changes the bar's orientation.
  45341. This won't change the bar's actual size - you'll need to do that yourself,
  45342. but this determines which direction the tabs go in, and which side they're
  45343. stuck to.
  45344. */
  45345. void setOrientation (Orientation orientation);
  45346. /** Returns the current orientation.
  45347. @see setOrientation
  45348. */
  45349. Orientation getOrientation() const noexcept { return orientation; }
  45350. /** Changes the minimum scale factor to which the tabs can be compressed when trying to
  45351. fit a lot of tabs on-screen.
  45352. */
  45353. void setMinimumTabScaleFactor (double newMinimumScale);
  45354. /** Deletes all the tabs from the bar.
  45355. @see addTab
  45356. */
  45357. void clearTabs();
  45358. /** Adds a tab to the bar.
  45359. Tabs are added in left-to-right reading order.
  45360. If this is the first tab added, it'll also be automatically selected.
  45361. */
  45362. void addTab (const String& tabName,
  45363. const Colour& tabBackgroundColour,
  45364. int insertIndex = -1);
  45365. /** Changes the name of one of the tabs. */
  45366. void setTabName (int tabIndex,
  45367. const String& newName);
  45368. /** Gets rid of one of the tabs. */
  45369. void removeTab (int tabIndex);
  45370. /** Moves a tab to a new index in the list.
  45371. Pass -1 as the index to move it to the end of the list.
  45372. */
  45373. void moveTab (int currentIndex, int newIndex);
  45374. /** Returns the number of tabs in the bar. */
  45375. int getNumTabs() const;
  45376. /** Returns a list of all the tab names in the bar. */
  45377. StringArray getTabNames() const;
  45378. /** Changes the currently selected tab.
  45379. This will send a change message and cause a synchronous callback to
  45380. the currentTabChanged() method. (But if the given tab is already selected,
  45381. nothing will be done).
  45382. To deselect all the tabs, use an index of -1.
  45383. */
  45384. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  45385. /** Returns the name of the currently selected tab.
  45386. This could be an empty string if none are selected.
  45387. */
  45388. String getCurrentTabName() const;
  45389. /** Returns the index of the currently selected tab.
  45390. This could return -1 if none are selected.
  45391. */
  45392. int getCurrentTabIndex() const noexcept { return currentTabIndex; }
  45393. /** Returns the button for a specific tab.
  45394. The button that is returned may be deleted later by this component, so don't hang
  45395. on to the pointer that is returned. A null pointer may be returned if the index is
  45396. out of range.
  45397. */
  45398. TabBarButton* getTabButton (int index) const;
  45399. /** Returns the index of a TabBarButton if it belongs to this bar. */
  45400. int indexOfTabButton (const TabBarButton* button) const;
  45401. /** Callback method to indicate the selected tab has been changed.
  45402. @see setCurrentTabIndex
  45403. */
  45404. virtual void currentTabChanged (int newCurrentTabIndex,
  45405. const String& newCurrentTabName);
  45406. /** Callback method to indicate that the user has right-clicked on a tab.
  45407. (Or ctrl-clicked on the Mac)
  45408. */
  45409. virtual void popupMenuClickOnTab (int tabIndex, const String& tabName);
  45410. /** Returns the colour of a tab.
  45411. This is the colour that was specified in addTab().
  45412. */
  45413. const Colour getTabBackgroundColour (int tabIndex);
  45414. /** Changes the background colour of a tab.
  45415. @see addTab, getTabBackgroundColour
  45416. */
  45417. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  45418. /** A set of colour IDs to use to change the colour of various aspects of the component.
  45419. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  45420. methods.
  45421. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  45422. */
  45423. enum ColourIds
  45424. {
  45425. tabOutlineColourId = 0x1005812, /**< The colour to use to draw an outline around the tabs. */
  45426. tabTextColourId = 0x1005813, /**< The colour to use to draw the tab names. If this isn't specified,
  45427. the look and feel will choose an appropriate colour. */
  45428. frontOutlineColourId = 0x1005814, /**< The colour to use to draw an outline around the currently-selected tab. */
  45429. frontTextColourId = 0x1005815, /**< The colour to use to draw the currently-selected tab name. If
  45430. this isn't specified, the look and feel will choose an appropriate
  45431. colour. */
  45432. };
  45433. /** @internal */
  45434. void resized();
  45435. /** @internal */
  45436. void lookAndFeelChanged();
  45437. protected:
  45438. /** This creates one of the tabs.
  45439. If you need to use custom tab components, you can override this method and
  45440. return your own class instead of the default.
  45441. */
  45442. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  45443. private:
  45444. Orientation orientation;
  45445. struct TabInfo
  45446. {
  45447. ScopedPointer<TabBarButton> component;
  45448. String name;
  45449. Colour colour;
  45450. };
  45451. OwnedArray <TabInfo> tabs;
  45452. double minimumScale;
  45453. int currentTabIndex;
  45454. class BehindFrontTabComp;
  45455. friend class BehindFrontTabComp;
  45456. friend class ScopedPointer<BehindFrontTabComp>;
  45457. ScopedPointer<BehindFrontTabComp> behindFrontTab;
  45458. ScopedPointer<Button> extraTabsButton;
  45459. void showExtraItemsMenu();
  45460. static void extraItemsMenuCallback (int, TabbedButtonBar*);
  45461. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabbedButtonBar);
  45462. };
  45463. #endif // __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  45464. /*** End of inlined file: juce_TabbedButtonBar.h ***/
  45465. /**
  45466. A component with a TabbedButtonBar along one of its sides.
  45467. This makes it easy to create a set of tabbed pages, just add a bunch of tabs
  45468. with addTab(), and this will take care of showing the pages for you when the
  45469. user clicks on a different tab.
  45470. @see TabbedButtonBar
  45471. */
  45472. class JUCE_API TabbedComponent : public Component
  45473. {
  45474. public:
  45475. /** Creates a TabbedComponent, specifying where the tabs should be placed.
  45476. Once created, add some tabs with the addTab() method.
  45477. */
  45478. explicit TabbedComponent (TabbedButtonBar::Orientation orientation);
  45479. /** Destructor. */
  45480. ~TabbedComponent();
  45481. /** Changes the placement of the tabs.
  45482. This will rearrange the layout to place the tabs along the appropriate
  45483. side of this component, and will shift the content component accordingly.
  45484. @see TabbedButtonBar::setOrientation
  45485. */
  45486. void setOrientation (TabbedButtonBar::Orientation orientation);
  45487. /** Returns the current tab placement.
  45488. @see setOrientation, TabbedButtonBar::getOrientation
  45489. */
  45490. TabbedButtonBar::Orientation getOrientation() const noexcept;
  45491. /** Specifies how many pixels wide or high the tab-bar should be.
  45492. If the tabs are placed along the top or bottom, this specified the height
  45493. of the bar; if they're along the left or right edges, it'll be the width
  45494. of the bar.
  45495. */
  45496. void setTabBarDepth (int newDepth);
  45497. /** Returns the current thickness of the tab bar.
  45498. @see setTabBarDepth
  45499. */
  45500. int getTabBarDepth() const noexcept { return tabDepth; }
  45501. /** Specifies the thickness of an outline that should be drawn around the content component.
  45502. If this thickness is > 0, a line will be drawn around the three sides of the content
  45503. component which don't touch the tab-bar, and the content component will be inset by this amount.
  45504. To set the colour of the line, use setColour (outlineColourId, ...).
  45505. */
  45506. void setOutline (int newThickness);
  45507. /** Specifies a gap to leave around the edge of the content component.
  45508. Each edge of the content component will be indented by the given number of pixels.
  45509. */
  45510. void setIndent (int indentThickness);
  45511. /** Removes all the tabs from the bar.
  45512. @see TabbedButtonBar::clearTabs
  45513. */
  45514. void clearTabs();
  45515. /** Adds a tab to the tab-bar.
  45516. The component passed in will be shown for the tab, and if deleteComponentWhenNotNeeded
  45517. is true, it will be deleted when the tab is removed or when this object is
  45518. deleted.
  45519. @see TabbedButtonBar::addTab
  45520. */
  45521. void addTab (const String& tabName,
  45522. const Colour& tabBackgroundColour,
  45523. Component* contentComponent,
  45524. bool deleteComponentWhenNotNeeded,
  45525. int insertIndex = -1);
  45526. /** Changes the name of one of the tabs. */
  45527. void setTabName (int tabIndex, const String& newName);
  45528. /** Gets rid of one of the tabs. */
  45529. void removeTab (int tabIndex);
  45530. /** Returns the number of tabs in the bar. */
  45531. int getNumTabs() const;
  45532. /** Returns a list of all the tab names in the bar. */
  45533. StringArray getTabNames() const;
  45534. /** Returns the content component that was added for the given index.
  45535. Be sure not to use or delete the components that are returned, as this may interfere
  45536. with the TabbedComponent's use of them.
  45537. */
  45538. Component* getTabContentComponent (int tabIndex) const noexcept;
  45539. /** Returns the colour of one of the tabs. */
  45540. const Colour getTabBackgroundColour (int tabIndex) const noexcept;
  45541. /** Changes the background colour of one of the tabs. */
  45542. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  45543. /** Changes the currently-selected tab.
  45544. To deselect all the tabs, pass -1 as the index.
  45545. @see TabbedButtonBar::setCurrentTabIndex
  45546. */
  45547. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  45548. /** Returns the index of the currently selected tab.
  45549. @see addTab, TabbedButtonBar::getCurrentTabIndex()
  45550. */
  45551. int getCurrentTabIndex() const;
  45552. /** Returns the name of the currently selected tab.
  45553. @see addTab, TabbedButtonBar::getCurrentTabName()
  45554. */
  45555. String getCurrentTabName() const;
  45556. /** Returns the current component that's filling the panel.
  45557. This will return 0 if there isn't one.
  45558. */
  45559. Component* getCurrentContentComponent() const noexcept { return panelComponent; }
  45560. /** Callback method to indicate the selected tab has been changed.
  45561. @see setCurrentTabIndex
  45562. */
  45563. virtual void currentTabChanged (int newCurrentTabIndex,
  45564. const String& newCurrentTabName);
  45565. /** Callback method to indicate that the user has right-clicked on a tab.
  45566. (Or ctrl-clicked on the Mac)
  45567. */
  45568. virtual void popupMenuClickOnTab (int tabIndex,
  45569. const String& tabName);
  45570. /** Returns the tab button bar component that is being used.
  45571. */
  45572. TabbedButtonBar& getTabbedButtonBar() const noexcept { return *tabs; }
  45573. /** A set of colour IDs to use to change the colour of various aspects of the component.
  45574. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  45575. methods.
  45576. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  45577. */
  45578. enum ColourIds
  45579. {
  45580. backgroundColourId = 0x1005800, /**< The colour to fill the background behind the tabs. */
  45581. outlineColourId = 0x1005801, /**< The colour to use to draw an outline around the content.
  45582. (See setOutline) */
  45583. };
  45584. /** @internal */
  45585. void paint (Graphics& g);
  45586. /** @internal */
  45587. void resized();
  45588. /** @internal */
  45589. void lookAndFeelChanged();
  45590. protected:
  45591. /** This creates one of the tab buttons.
  45592. If you need to use custom tab components, you can override this method and
  45593. return your own class instead of the default.
  45594. */
  45595. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  45596. /** @internal */
  45597. ScopedPointer<TabbedButtonBar> tabs;
  45598. private:
  45599. Array <WeakReference<Component> > contentComponents;
  45600. WeakReference<Component> panelComponent;
  45601. int tabDepth;
  45602. int outlineThickness, edgeIndent;
  45603. class ButtonBar;
  45604. friend class ButtonBar;
  45605. void changeCallback (int newCurrentTabIndex, const String& newTabName);
  45606. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabbedComponent);
  45607. };
  45608. #endif // __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  45609. /*** End of inlined file: juce_TabbedComponent.h ***/
  45610. /*** Start of inlined file: juce_DocumentWindow.h ***/
  45611. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  45612. #define __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  45613. /*** Start of inlined file: juce_MenuBarModel.h ***/
  45614. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  45615. #define __JUCE_MENUBARMODEL_JUCEHEADER__
  45616. /**
  45617. A class for controlling MenuBar components.
  45618. This class is used to tell a MenuBar what menus to show, and to respond
  45619. to a menu being selected.
  45620. @see MenuBarModel::Listener, MenuBarComponent, PopupMenu
  45621. */
  45622. class JUCE_API MenuBarModel : private AsyncUpdater,
  45623. private ApplicationCommandManagerListener
  45624. {
  45625. public:
  45626. MenuBarModel() noexcept;
  45627. /** Destructor. */
  45628. virtual ~MenuBarModel();
  45629. /** Call this when some of your menu items have changed.
  45630. This method will cause a callback to any MenuBarListener objects that
  45631. are registered with this model.
  45632. If this model is displaying items from an ApplicationCommandManager, you
  45633. can use the setApplicationCommandManagerToWatch() method to cause
  45634. change messages to be sent automatically when the ApplicationCommandManager
  45635. is changed.
  45636. @see addListener, removeListener, MenuBarListener
  45637. */
  45638. void menuItemsChanged();
  45639. /** Tells the menu bar to listen to the specified command manager, and to update
  45640. itself when the commands change.
  45641. This will also allow it to flash a menu name when a command from that menu
  45642. is invoked using a keystroke.
  45643. */
  45644. void setApplicationCommandManagerToWatch (ApplicationCommandManager* manager) noexcept;
  45645. /** A class to receive callbacks when a MenuBarModel changes.
  45646. @see MenuBarModel::addListener, MenuBarModel::removeListener, MenuBarModel::menuItemsChanged
  45647. */
  45648. class JUCE_API Listener
  45649. {
  45650. public:
  45651. /** Destructor. */
  45652. virtual ~Listener() {}
  45653. /** This callback is made when items are changed in the menu bar model.
  45654. */
  45655. virtual void menuBarItemsChanged (MenuBarModel* menuBarModel) = 0;
  45656. /** This callback is made when an application command is invoked that
  45657. is represented by one of the items in the menu bar model.
  45658. */
  45659. virtual void menuCommandInvoked (MenuBarModel* menuBarModel,
  45660. const ApplicationCommandTarget::InvocationInfo& info) = 0;
  45661. };
  45662. /** Registers a listener for callbacks when the menu items in this model change.
  45663. The listener object will get callbacks when this object's menuItemsChanged()
  45664. method is called.
  45665. @see removeListener
  45666. */
  45667. void addListener (Listener* listenerToAdd) noexcept;
  45668. /** Removes a listener.
  45669. @see addListener
  45670. */
  45671. void removeListener (Listener* listenerToRemove) noexcept;
  45672. /** This method must return a list of the names of the menus. */
  45673. virtual const StringArray getMenuBarNames() = 0;
  45674. /** This should return the popup menu to display for a given top-level menu.
  45675. @param topLevelMenuIndex the index of the top-level menu to show
  45676. @param menuName the name of the top-level menu item to show
  45677. */
  45678. virtual const PopupMenu getMenuForIndex (int topLevelMenuIndex,
  45679. const String& menuName) = 0;
  45680. /** This is called when a menu item has been clicked on.
  45681. @param menuItemID the item ID of the PopupMenu item that was selected
  45682. @param topLevelMenuIndex the index of the top-level menu from which the item was
  45683. chosen (just in case you've used duplicate ID numbers
  45684. on more than one of the popup menus)
  45685. */
  45686. virtual void menuItemSelected (int menuItemID,
  45687. int topLevelMenuIndex) = 0;
  45688. #if JUCE_MAC || DOXYGEN
  45689. /** MAC ONLY - Sets the model that is currently being shown as the main
  45690. menu bar at the top of the screen on the Mac.
  45691. You can pass 0 to stop the current model being displayed. Be careful
  45692. not to delete a model while it is being used.
  45693. An optional extra menu can be specified, containing items to add to the top of
  45694. the apple menu. (Confusingly, the 'apple' menu isn't the one with a picture of
  45695. an apple, it's the one next to it, with your application's name at the top
  45696. and the services menu etc on it). When one of these items is selected, the
  45697. menu bar model will be used to invoke it, and in the menuItemSelected() callback
  45698. the topLevelMenuIndex parameter will be -1. If you pass in an extraAppleMenuItems
  45699. object then newMenuBarModel must be non-null.
  45700. */
  45701. static void setMacMainMenu (MenuBarModel* newMenuBarModel,
  45702. const PopupMenu* extraAppleMenuItems = nullptr);
  45703. /** MAC ONLY - Returns the menu model that is currently being shown as
  45704. the main menu bar.
  45705. */
  45706. static MenuBarModel* getMacMainMenu();
  45707. #endif
  45708. /** @internal */
  45709. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info);
  45710. /** @internal */
  45711. void applicationCommandListChanged();
  45712. /** @internal */
  45713. void handleAsyncUpdate();
  45714. private:
  45715. ApplicationCommandManager* manager;
  45716. ListenerList <Listener> listeners;
  45717. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuBarModel);
  45718. };
  45719. /** This typedef is just for compatibility with old code - newer code should use the MenuBarModel::Listener class directly. */
  45720. typedef MenuBarModel::Listener MenuBarModelListener;
  45721. #endif // __JUCE_MENUBARMODEL_JUCEHEADER__
  45722. /*** End of inlined file: juce_MenuBarModel.h ***/
  45723. /**
  45724. A resizable window with a title bar and maximise, minimise and close buttons.
  45725. This subclass of ResizableWindow creates a fairly standard type of window with
  45726. a title bar and various buttons. The name of the component is shown in the
  45727. title bar, and an icon can optionally be specified with setIcon().
  45728. All the methods available to a ResizableWindow are also available to this,
  45729. so it can easily be made resizable, minimised, maximised, etc.
  45730. It's not advisable to add child components directly to a DocumentWindow: put them
  45731. inside your content component instead. And overriding methods like resized(), moved(), etc
  45732. is also not recommended - instead override these methods for your content component.
  45733. (If for some obscure reason you do need to override these methods, always remember to
  45734. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  45735. decorations correctly).
  45736. You can also automatically add a menu bar to the window, using the setMenuBar()
  45737. method.
  45738. @see ResizableWindow, DialogWindow
  45739. */
  45740. class JUCE_API DocumentWindow : public ResizableWindow
  45741. {
  45742. public:
  45743. /** The set of available button-types that can be put on the title bar.
  45744. @see setTitleBarButtonsRequired
  45745. */
  45746. enum TitleBarButtons
  45747. {
  45748. minimiseButton = 1,
  45749. maximiseButton = 2,
  45750. closeButton = 4,
  45751. /** A combination of all the buttons above. */
  45752. allButtons = 7
  45753. };
  45754. /** Creates a DocumentWindow.
  45755. @param name the name to give the component - this is also
  45756. the title shown at the top of the window. To change
  45757. this later, use setName()
  45758. @param backgroundColour the colour to use for filling the window's background.
  45759. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  45760. should be shown on the title bar. This value is a bitwise
  45761. combination of values from the TitleBarButtons enum. Note
  45762. that it can be "allButtons" to get them all. You
  45763. can change this later with the setTitleBarButtonsRequired()
  45764. method, which can also specify where they are positioned.
  45765. @param addToDesktop if true, the window will be automatically added to the
  45766. desktop; if false, you can use it as a child component
  45767. @see TitleBarButtons
  45768. */
  45769. DocumentWindow (const String& name,
  45770. const Colour& backgroundColour,
  45771. int requiredButtons,
  45772. bool addToDesktop = true);
  45773. /** Destructor.
  45774. If a content component has been set with setContentOwned(), it will be deleted.
  45775. */
  45776. ~DocumentWindow();
  45777. /** Changes the component's name.
  45778. (This is overridden from Component::setName() to cause a repaint, as
  45779. the name is what gets drawn across the window's title bar).
  45780. */
  45781. void setName (const String& newName);
  45782. /** Sets an icon to show in the title bar, next to the title.
  45783. A copy is made internally of the image, so the caller can delete the
  45784. image after calling this. If 0 is passed-in, any existing icon will be
  45785. removed.
  45786. */
  45787. void setIcon (const Image& imageToUse);
  45788. /** Changes the height of the title-bar. */
  45789. void setTitleBarHeight (int newHeight);
  45790. /** Returns the current title bar height. */
  45791. int getTitleBarHeight() const;
  45792. /** Changes the set of title-bar buttons being shown.
  45793. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  45794. should be shown on the title bar. This value is a bitwise
  45795. combination of values from the TitleBarButtons enum. Note
  45796. that it can be "allButtons" to get them all.
  45797. @param positionTitleBarButtonsOnLeft if true, the buttons should go at the
  45798. left side of the bar; if false, they'll be placed at the right
  45799. */
  45800. void setTitleBarButtonsRequired (int requiredButtons,
  45801. bool positionTitleBarButtonsOnLeft);
  45802. /** Sets whether the title should be centred within the window.
  45803. If true, the title text is shown in the middle of the title-bar; if false,
  45804. it'll be shown at the left of the bar.
  45805. */
  45806. void setTitleBarTextCentred (bool textShouldBeCentred);
  45807. /** Creates a menu inside this window.
  45808. @param menuBarModel this specifies a MenuBarModel that should be used to
  45809. generate the contents of a menu bar that will be placed
  45810. just below the title bar, and just above any content
  45811. component. If this value is zero, any existing menu bar
  45812. will be removed from the component; if non-zero, one will
  45813. be added if it's required.
  45814. @param menuBarHeight the height of the menu bar component, if one is needed. Pass a value of zero
  45815. or less to use the look-and-feel's default size.
  45816. */
  45817. void setMenuBar (MenuBarModel* menuBarModel,
  45818. int menuBarHeight = 0);
  45819. /** Returns the current menu bar component, or null if there isn't one.
  45820. This is probably a MenuBarComponent, unless a custom one has been set using
  45821. setMenuBarComponent().
  45822. */
  45823. Component* getMenuBarComponent() const noexcept;
  45824. /** Replaces the current menu bar with a custom component.
  45825. The component will be owned and deleted by the document window.
  45826. */
  45827. void setMenuBarComponent (Component* newMenuBarComponent);
  45828. /** This method is called when the user tries to close the window.
  45829. This is triggered by the user clicking the close button, or using some other
  45830. OS-specific key shortcut or OS menu for getting rid of a window.
  45831. If the window is just a pop-up, you should override this closeButtonPressed()
  45832. method and make it delete the window in whatever way is appropriate for your
  45833. app. E.g. you might just want to call "delete this".
  45834. If your app is centred around this window such that the whole app should quit when
  45835. the window is closed, then you will probably want to use this method as an opportunity
  45836. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  45837. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  45838. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  45839. or closing it via the taskbar icon on Windows).
  45840. (Note that the DocumentWindow class overrides Component::userTriedToCloseWindow() and
  45841. redirects it to call this method, so any methods of closing the window that are
  45842. caught by userTriedToCloseWindow() will also end up here).
  45843. */
  45844. virtual void closeButtonPressed();
  45845. /** Callback that is triggered when the minimise button is pressed.
  45846. The default implementation of this calls ResizableWindow::setMinimised(), but
  45847. you can override it to do more customised behaviour.
  45848. */
  45849. virtual void minimiseButtonPressed();
  45850. /** Callback that is triggered when the maximise button is pressed, or when the
  45851. title-bar is double-clicked.
  45852. The default implementation of this calls ResizableWindow::setFullScreen(), but
  45853. you can override it to do more customised behaviour.
  45854. */
  45855. virtual void maximiseButtonPressed();
  45856. /** Returns the close button, (or 0 if there isn't one). */
  45857. Button* getCloseButton() const noexcept;
  45858. /** Returns the minimise button, (or 0 if there isn't one). */
  45859. Button* getMinimiseButton() const noexcept;
  45860. /** Returns the maximise button, (or 0 if there isn't one). */
  45861. Button* getMaximiseButton() const noexcept;
  45862. /** A set of colour IDs to use to change the colour of various aspects of the window.
  45863. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  45864. methods.
  45865. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  45866. */
  45867. enum ColourIds
  45868. {
  45869. textColourId = 0x1005701, /**< The colour to draw any text with. It's up to the look
  45870. and feel class how this is used. */
  45871. };
  45872. #ifndef DOXYGEN
  45873. /** @internal */
  45874. void paint (Graphics& g);
  45875. /** @internal */
  45876. void resized();
  45877. /** @internal */
  45878. void lookAndFeelChanged();
  45879. /** @internal */
  45880. const BorderSize<int> getBorderThickness();
  45881. /** @internal */
  45882. const BorderSize<int> getContentComponentBorder();
  45883. /** @internal */
  45884. void mouseDoubleClick (const MouseEvent& e);
  45885. /** @internal */
  45886. void userTriedToCloseWindow();
  45887. /** @internal */
  45888. void activeWindowStatusChanged();
  45889. /** @internal */
  45890. int getDesktopWindowStyleFlags() const;
  45891. /** @internal */
  45892. void parentHierarchyChanged();
  45893. /** @internal */
  45894. const Rectangle<int> getTitleBarArea();
  45895. #endif
  45896. private:
  45897. int titleBarHeight, menuBarHeight, requiredButtons;
  45898. bool positionTitleBarButtonsOnLeft, drawTitleTextCentred;
  45899. ScopedPointer <Button> titleBarButtons [3];
  45900. Image titleBarIcon;
  45901. ScopedPointer <Component> menuBar;
  45902. MenuBarModel* menuBarModel;
  45903. class ButtonListenerProxy;
  45904. friend class ScopedPointer <ButtonListenerProxy>;
  45905. ScopedPointer <ButtonListenerProxy> buttonListener;
  45906. void repaintTitleBar();
  45907. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DocumentWindow);
  45908. };
  45909. #endif // __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  45910. /*** End of inlined file: juce_DocumentWindow.h ***/
  45911. class MultiDocumentPanel;
  45912. class MDITabbedComponentInternal;
  45913. /**
  45914. This is a derivative of DocumentWindow that is used inside a MultiDocumentPanel
  45915. component.
  45916. It's like a normal DocumentWindow but has some extra functionality to make sure
  45917. everything works nicely inside a MultiDocumentPanel.
  45918. @see MultiDocumentPanel
  45919. */
  45920. class JUCE_API MultiDocumentPanelWindow : public DocumentWindow
  45921. {
  45922. public:
  45923. /**
  45924. */
  45925. MultiDocumentPanelWindow (const Colour& backgroundColour);
  45926. /** Destructor. */
  45927. ~MultiDocumentPanelWindow();
  45928. /** @internal */
  45929. void maximiseButtonPressed();
  45930. /** @internal */
  45931. void closeButtonPressed();
  45932. /** @internal */
  45933. void activeWindowStatusChanged();
  45934. /** @internal */
  45935. void broughtToFront();
  45936. private:
  45937. void updateOrder();
  45938. MultiDocumentPanel* getOwner() const noexcept;
  45939. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MultiDocumentPanelWindow);
  45940. };
  45941. /**
  45942. A component that contains a set of other components either in floating windows
  45943. or tabs.
  45944. This acts as a panel that can be used to hold a set of open document windows, with
  45945. different layout modes.
  45946. Use addDocument() and closeDocument() to add or remove components from the
  45947. panel - never use any of the Component methods to access the panel's child
  45948. components directly, as these are managed internally.
  45949. */
  45950. class JUCE_API MultiDocumentPanel : public Component,
  45951. private ComponentListener
  45952. {
  45953. public:
  45954. /** Creates an empty panel.
  45955. Use addDocument() and closeDocument() to add or remove components from the
  45956. panel - never use any of the Component methods to access the panel's child
  45957. components directly, as these are managed internally.
  45958. */
  45959. MultiDocumentPanel();
  45960. /** Destructor.
  45961. When deleted, this will call closeAllDocuments (false) to make sure all its
  45962. components are deleted. If you need to make sure all documents are saved
  45963. before closing, then you should call closeAllDocuments (true) and check that
  45964. it returns true before deleting the panel.
  45965. */
  45966. ~MultiDocumentPanel();
  45967. /** Tries to close all the documents.
  45968. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  45969. be called for each open document, and any of these calls fails, this method
  45970. will stop and return false, leaving some documents still open.
  45971. If checkItsOkToCloseFirst is false, then all documents will be closed
  45972. unconditionally.
  45973. @see closeDocument
  45974. */
  45975. bool closeAllDocuments (bool checkItsOkToCloseFirst);
  45976. /** Adds a document component to the panel.
  45977. If the number of documents would exceed the limit set by setMaximumNumDocuments() then
  45978. this will fail and return false. (If it does fail, the component passed-in will not be
  45979. deleted, even if deleteWhenRemoved was set to true).
  45980. The MultiDocumentPanel will deal with creating a window border to go around your component,
  45981. so just pass in the bare content component here, no need to give it a ResizableWindow
  45982. or DocumentWindow.
  45983. @param component the component to add
  45984. @param backgroundColour the background colour to use to fill the component's
  45985. window or tab
  45986. @param deleteWhenRemoved if true, then when the component is removed by closeDocument()
  45987. or closeAllDocuments(), then it will be deleted. If false, then
  45988. the caller must handle the component's deletion
  45989. */
  45990. bool addDocument (Component* component,
  45991. const Colour& backgroundColour,
  45992. bool deleteWhenRemoved);
  45993. /** Closes one of the documents.
  45994. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  45995. be called, and if it fails, this method will return false without closing the
  45996. document.
  45997. If checkItsOkToCloseFirst is false, then the documents will be closed
  45998. unconditionally.
  45999. The component will be deleted if the deleteWhenRemoved parameter was set to
  46000. true when it was added with addDocument.
  46001. @see addDocument, closeAllDocuments
  46002. */
  46003. bool closeDocument (Component* component,
  46004. bool checkItsOkToCloseFirst);
  46005. /** Returns the number of open document windows.
  46006. @see getDocument
  46007. */
  46008. int getNumDocuments() const noexcept;
  46009. /** Returns one of the open documents.
  46010. The order of the documents in this array may change when they are added, removed
  46011. or moved around.
  46012. @see getNumDocuments
  46013. */
  46014. Component* getDocument (int index) const noexcept;
  46015. /** Returns the document component that is currently focused or on top.
  46016. If currently using floating windows, then this will be the component in the currently
  46017. active window, or the top component if none are active.
  46018. If it's currently in tabbed mode, then it'll return the component in the active tab.
  46019. @see setActiveDocument
  46020. */
  46021. Component* getActiveDocument() const noexcept;
  46022. /** Makes one of the components active and brings it to the top.
  46023. @see getActiveDocument
  46024. */
  46025. void setActiveDocument (Component* component);
  46026. /** Callback which gets invoked when the currently-active document changes. */
  46027. virtual void activeDocumentChanged();
  46028. /** Sets a limit on how many windows can be open at once.
  46029. If this is zero or less there's no limit (the default). addDocument() will fail
  46030. if this number is exceeded.
  46031. */
  46032. void setMaximumNumDocuments (int maximumNumDocuments);
  46033. /** Sets an option to make the document fullscreen if there's only one document open.
  46034. If set to true, then if there's only one document, it'll fill the whole of this
  46035. component without tabs or a window border. If false, then tabs or a window
  46036. will always be shown, even if there's only one document. If there's more than
  46037. one document open, then this option makes no difference.
  46038. */
  46039. void useFullscreenWhenOneDocument (bool shouldUseTabs);
  46040. /** Returns the result of the last time useFullscreenWhenOneDocument() was called.
  46041. */
  46042. bool isFullscreenWhenOneDocument() const noexcept;
  46043. /** The different layout modes available. */
  46044. enum LayoutMode
  46045. {
  46046. FloatingWindows, /**< In this mode, there are overlapping DocumentWindow components for each document. */
  46047. MaximisedWindowsWithTabs /**< In this mode, a TabbedComponent is used to show one document at a time. */
  46048. };
  46049. /** Changes the panel's mode.
  46050. @see LayoutMode, getLayoutMode
  46051. */
  46052. void setLayoutMode (LayoutMode newLayoutMode);
  46053. /** Returns the current layout mode. */
  46054. LayoutMode getLayoutMode() const noexcept { return mode; }
  46055. /** Sets the background colour for the whole panel.
  46056. Each document has its own background colour, but this is the one used to fill the areas
  46057. behind them.
  46058. */
  46059. void setBackgroundColour (const Colour& newBackgroundColour);
  46060. /** Returns the current background colour.
  46061. @see setBackgroundColour
  46062. */
  46063. const Colour& getBackgroundColour() const noexcept { return backgroundColour; }
  46064. /** A subclass must override this to say whether its currently ok for a document
  46065. to be closed.
  46066. This method is called by closeDocument() and closeAllDocuments() to indicate that
  46067. a document should be saved if possible, ready for it to be closed.
  46068. If this method returns true, then it means the document is ok and can be closed.
  46069. If it returns false, then it means that the closeDocument() method should stop
  46070. and not close.
  46071. Normally, you'd use this method to ask the user if they want to save any changes,
  46072. then return true if the save operation went ok. If the user cancelled the save
  46073. operation you could return false here to abort the close operation.
  46074. If your component is based on the FileBasedDocument class, then you'd probably want
  46075. to call FileBasedDocument::saveIfNeededAndUserAgrees() and return true if this returned
  46076. FileBasedDocument::savedOk
  46077. @see closeDocument, FileBasedDocument::saveIfNeededAndUserAgrees()
  46078. */
  46079. virtual bool tryToCloseDocument (Component* component) = 0;
  46080. /** Creates a new window to be used for a document.
  46081. The default implementation of this just returns a basic MultiDocumentPanelWindow object,
  46082. but you might want to override it to return a custom component.
  46083. */
  46084. virtual MultiDocumentPanelWindow* createNewDocumentWindow();
  46085. /** @internal */
  46086. void paint (Graphics& g);
  46087. /** @internal */
  46088. void resized();
  46089. /** @internal */
  46090. void componentNameChanged (Component&);
  46091. private:
  46092. LayoutMode mode;
  46093. Array <Component*> components;
  46094. ScopedPointer<TabbedComponent> tabComponent;
  46095. Colour backgroundColour;
  46096. int maximumNumDocuments, numDocsBeforeTabsUsed;
  46097. friend class MultiDocumentPanelWindow;
  46098. friend class MDITabbedComponentInternal;
  46099. Component* getContainerComp (Component* c) const;
  46100. void updateOrder();
  46101. void addWindow (Component* component);
  46102. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MultiDocumentPanel);
  46103. };
  46104. #endif // __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  46105. /*** End of inlined file: juce_MultiDocumentPanel.h ***/
  46106. #endif
  46107. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  46108. #endif
  46109. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  46110. #endif
  46111. #ifndef __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  46112. /*** Start of inlined file: juce_ResizableEdgeComponent.h ***/
  46113. #ifndef __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  46114. #define __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  46115. /**
  46116. A component that resizes its parent component when dragged.
  46117. This component forms a bar along one edge of a component, allowing it to
  46118. be dragged by that edges to resize it.
  46119. To use it, just add it to your component, positioning it along the appropriate
  46120. edge. Make sure you reposition the resizer component each time the parent's size
  46121. changes, to keep it in the correct position.
  46122. @see ResizbleBorderComponent, ResizableCornerComponent
  46123. */
  46124. class JUCE_API ResizableEdgeComponent : public Component
  46125. {
  46126. public:
  46127. enum Edge
  46128. {
  46129. leftEdge, /**< Indicates a vertical bar that can be dragged left/right to move the component's left-hand edge. */
  46130. rightEdge, /**< Indicates a vertical bar that can be dragged left/right to move the component's right-hand edge. */
  46131. topEdge, /**< Indicates a horizontal bar that can be dragged up/down to move the top of the component. */
  46132. bottomEdge /**< Indicates a horizontal bar that can be dragged up/down to move the bottom of the component. */
  46133. };
  46134. /** Creates a resizer bar.
  46135. Pass in the target component which you want to be resized when this one is
  46136. dragged. The target component will usually be this component's parent, but this
  46137. isn't mandatory.
  46138. Remember that when the target component is resized, it'll need to move and
  46139. resize this component to keep it in place, as this won't happen automatically.
  46140. If the constrainer parameter is non-zero, then this object will be used to enforce
  46141. limits on the size and position that the component can be stretched to. Make sure
  46142. that the constrainer isn't deleted while still in use by this object.
  46143. @see ComponentBoundsConstrainer
  46144. */
  46145. ResizableEdgeComponent (Component* componentToResize,
  46146. ComponentBoundsConstrainer* constrainer,
  46147. Edge edgeToResize);
  46148. /** Destructor. */
  46149. ~ResizableEdgeComponent();
  46150. bool isVertical() const noexcept;
  46151. protected:
  46152. /** @internal */
  46153. void paint (Graphics& g);
  46154. /** @internal */
  46155. void mouseDown (const MouseEvent& e);
  46156. /** @internal */
  46157. void mouseDrag (const MouseEvent& e);
  46158. /** @internal */
  46159. void mouseUp (const MouseEvent& e);
  46160. private:
  46161. WeakReference<Component> component;
  46162. ComponentBoundsConstrainer* constrainer;
  46163. Rectangle<int> originalBounds;
  46164. const Edge edge;
  46165. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableEdgeComponent);
  46166. };
  46167. #endif // __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  46168. /*** End of inlined file: juce_ResizableEdgeComponent.h ***/
  46169. #endif
  46170. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  46171. #endif
  46172. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  46173. /*** Start of inlined file: juce_StretchableLayoutManager.h ***/
  46174. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  46175. #define __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  46176. /**
  46177. For laying out a set of components, where the components have preferred sizes
  46178. and size limits, but where they are allowed to stretch to fill the available
  46179. space.
  46180. For example, if you have a component containing several other components, and
  46181. each one should be given a share of the total size, you could use one of these
  46182. to resize the child components when the parent component is resized. Then
  46183. you could add a StretchableLayoutResizerBar to easily let the user rescale them.
  46184. A StretchableLayoutManager operates only in one dimension, so if you have a set
  46185. of components stacked vertically on top of each other, you'd use one to manage their
  46186. heights. To build up complex arrangements of components, e.g. for applications
  46187. with multiple nested panels, you would use more than one StretchableLayoutManager.
  46188. E.g. by using two (one vertical, one horizontal), you could create a resizable
  46189. spreadsheet-style table.
  46190. E.g.
  46191. @code
  46192. class MyComp : public Component
  46193. {
  46194. StretchableLayoutManager myLayout;
  46195. MyComp()
  46196. {
  46197. myLayout.setItemLayout (0, // for item 0
  46198. 50, 100, // must be between 50 and 100 pixels in size
  46199. -0.6); // and its preferred size is 60% of the total available space
  46200. myLayout.setItemLayout (1, // for item 1
  46201. -0.2, -0.6, // size must be between 20% and 60% of the available space
  46202. 50); // and its preferred size is 50 pixels
  46203. }
  46204. void resized()
  46205. {
  46206. // make a list of two of our child components that we want to reposition
  46207. Component* comps[] = { myComp1, myComp2 };
  46208. // this will position the 2 components, one above the other, to fit
  46209. // vertically into the rectangle provided.
  46210. myLayout.layOutComponents (comps, 2,
  46211. 0, 0, getWidth(), getHeight(),
  46212. true);
  46213. }
  46214. };
  46215. @endcode
  46216. @see StretchableLayoutResizerBar
  46217. */
  46218. class JUCE_API StretchableLayoutManager
  46219. {
  46220. public:
  46221. /** Creates an empty layout.
  46222. You'll need to add some item properties to the layout before it can be used
  46223. to resize things - see setItemLayout().
  46224. */
  46225. StretchableLayoutManager();
  46226. /** Destructor. */
  46227. ~StretchableLayoutManager();
  46228. /** For a numbered item, this sets its size limits and preferred size.
  46229. @param itemIndex the index of the item to change.
  46230. @param minimumSize the minimum size that this item is allowed to be - a positive number
  46231. indicates an absolute size in pixels. A negative number indicates a
  46232. proportion of the available space (e.g -0.5 is 50%)
  46233. @param maximumSize the maximum size that this item is allowed to be - a positive number
  46234. indicates an absolute size in pixels. A negative number indicates a
  46235. proportion of the available space
  46236. @param preferredSize the size that this item would like to be, if there's enough room. A
  46237. positive number indicates an absolute size in pixels. A negative number
  46238. indicates a proportion of the available space
  46239. @see getItemLayout
  46240. */
  46241. void setItemLayout (int itemIndex,
  46242. double minimumSize,
  46243. double maximumSize,
  46244. double preferredSize);
  46245. /** For a numbered item, this returns its size limits and preferred size.
  46246. @param itemIndex the index of the item.
  46247. @param minimumSize the minimum size that this item is allowed to be - a positive number
  46248. indicates an absolute size in pixels. A negative number indicates a
  46249. proportion of the available space (e.g -0.5 is 50%)
  46250. @param maximumSize the maximum size that this item is allowed to be - a positive number
  46251. indicates an absolute size in pixels. A negative number indicates a
  46252. proportion of the available space
  46253. @param preferredSize the size that this item would like to be, if there's enough room. A
  46254. positive number indicates an absolute size in pixels. A negative number
  46255. indicates a proportion of the available space
  46256. @returns false if the item's properties hadn't been set
  46257. @see setItemLayout
  46258. */
  46259. bool getItemLayout (int itemIndex,
  46260. double& minimumSize,
  46261. double& maximumSize,
  46262. double& preferredSize) const;
  46263. /** Clears all the properties that have been set with setItemLayout() and resets
  46264. this object to its initial state.
  46265. */
  46266. void clearAllItems();
  46267. /** Takes a set of components that correspond to the layout's items, and positions
  46268. them to fill a space.
  46269. This will try to give each item its preferred size, whether that's a relative size
  46270. or an absolute one.
  46271. @param components an array of components that correspond to each of the
  46272. numbered items that the StretchableLayoutManager object
  46273. has been told about with setItemLayout()
  46274. @param numComponents the number of components in the array that is passed-in. This
  46275. should be the same as the number of items this object has been
  46276. told about.
  46277. @param x the left of the rectangle in which the components should
  46278. be laid out
  46279. @param y the top of the rectangle in which the components should
  46280. be laid out
  46281. @param width the width of the rectangle in which the components should
  46282. be laid out
  46283. @param height the height of the rectangle in which the components should
  46284. be laid out
  46285. @param vertically if true, the components will be positioned in a vertical stack,
  46286. so that they fill the height of the rectangle. If false, they
  46287. will be placed side-by-side in a horizontal line, filling the
  46288. available width
  46289. @param resizeOtherDimension if true, this means that the components will have their
  46290. other dimension resized to fit the space - i.e. if the 'vertically'
  46291. parameter is true, their x-positions and widths are adjusted to fit
  46292. the x and width parameters; if 'vertically' is false, their y-positions
  46293. and heights are adjusted to fit the y and height parameters.
  46294. */
  46295. void layOutComponents (Component** components,
  46296. int numComponents,
  46297. int x, int y, int width, int height,
  46298. bool vertically,
  46299. bool resizeOtherDimension);
  46300. /** Returns the current position of one of the items.
  46301. This is only a valid call after layOutComponents() has been called, as it
  46302. returns the last position that this item was placed at. If the layout was
  46303. vertical, the value returned will be the y position of the top of the item,
  46304. relative to the top of the rectangle in which the items were placed (so for
  46305. example, item 0 will always have position of 0, even in the rectangle passed
  46306. in to layOutComponents() wasn't at y = 0). If the layout was done horizontally,
  46307. the position returned is the item's left-hand position, again relative to the
  46308. x position of the rectangle used.
  46309. @see getItemCurrentSize, setItemPosition
  46310. */
  46311. int getItemCurrentPosition (int itemIndex) const;
  46312. /** Returns the current size of one of the items.
  46313. This is only meaningful after layOutComponents() has been called, as it
  46314. returns the last size that this item was given. If the layout was done
  46315. vertically, it'll return the item's height in pixels; if it was horizontal,
  46316. it'll return its width.
  46317. @see getItemCurrentRelativeSize
  46318. */
  46319. int getItemCurrentAbsoluteSize (int itemIndex) const;
  46320. /** Returns the current size of one of the items.
  46321. This is only meaningful after layOutComponents() has been called, as it
  46322. returns the last size that this item was given. If the layout was done
  46323. vertically, it'll return a negative value representing the item's height relative
  46324. to the last size used for laying the components out; if the layout was done
  46325. horizontally it'll be the proportion of its width.
  46326. @see getItemCurrentAbsoluteSize
  46327. */
  46328. double getItemCurrentRelativeSize (int itemIndex) const;
  46329. /** Moves one of the items, shifting along any other items as necessary in
  46330. order to get it to the desired position.
  46331. Calling this method will also update the preferred sizes of the items it
  46332. shuffles along, so that they reflect their new positions.
  46333. (This is the method that a StretchableLayoutResizerBar uses to shift the items
  46334. about when it's dragged).
  46335. @param itemIndex the item to move
  46336. @param newPosition the absolute position that you'd like this item to move
  46337. to. The item might not be able to always reach exactly this position,
  46338. because other items may have minimum sizes that constrain how
  46339. far it can go
  46340. */
  46341. void setItemPosition (int itemIndex,
  46342. int newPosition);
  46343. private:
  46344. struct ItemLayoutProperties
  46345. {
  46346. int itemIndex;
  46347. int currentSize;
  46348. double minSize, maxSize, preferredSize;
  46349. };
  46350. OwnedArray <ItemLayoutProperties> items;
  46351. int totalSize;
  46352. static int sizeToRealSize (double size, int totalSpace);
  46353. ItemLayoutProperties* getInfoFor (int itemIndex) const;
  46354. void setTotalSize (int newTotalSize);
  46355. int fitComponentsIntoSpace (int startIndex, int endIndex, int availableSpace, int startPos);
  46356. int getMinimumSizeOfItems (int startIndex, int endIndex) const;
  46357. int getMaximumSizeOfItems (int startIndex, int endIndex) const;
  46358. void updatePrefSizesToMatchCurrentPositions();
  46359. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StretchableLayoutManager);
  46360. };
  46361. #endif // __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  46362. /*** End of inlined file: juce_StretchableLayoutManager.h ***/
  46363. #endif
  46364. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  46365. /*** Start of inlined file: juce_StretchableLayoutResizerBar.h ***/
  46366. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  46367. #define __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  46368. /**
  46369. A component that acts as one of the vertical or horizontal bars you see being
  46370. used to resize panels in a window.
  46371. One of these acts with a StretchableLayoutManager to resize the other components.
  46372. @see StretchableLayoutManager
  46373. */
  46374. class JUCE_API StretchableLayoutResizerBar : public Component
  46375. {
  46376. public:
  46377. /** Creates a resizer bar for use on a specified layout.
  46378. @param layoutToUse the layout that will be affected when this bar
  46379. is dragged
  46380. @param itemIndexInLayout the item index in the layout that corresponds to
  46381. this bar component. You'll need to set up the item
  46382. properties in a suitable way for a divider bar, e.g.
  46383. for an 8-pixel wide bar which, you could call
  46384. myLayout->setItemLayout (barIndex, 8, 8, 8)
  46385. @param isBarVertical true if it's an upright bar that you drag left and
  46386. right; false for a horizontal one that you drag up and
  46387. down
  46388. */
  46389. StretchableLayoutResizerBar (StretchableLayoutManager* layoutToUse,
  46390. int itemIndexInLayout,
  46391. bool isBarVertical);
  46392. /** Destructor. */
  46393. ~StretchableLayoutResizerBar();
  46394. /** This is called when the bar is dragged.
  46395. This method must update the positions of any components whose position is
  46396. determined by the StretchableLayoutManager, because they might have just
  46397. moved.
  46398. The default implementation calls the resized() method of this component's
  46399. parent component, because that's often where you're likely to apply the
  46400. layout, but it can be overridden for more specific needs.
  46401. */
  46402. virtual void hasBeenMoved();
  46403. /** @internal */
  46404. void paint (Graphics& g);
  46405. /** @internal */
  46406. void mouseDown (const MouseEvent& e);
  46407. /** @internal */
  46408. void mouseDrag (const MouseEvent& e);
  46409. private:
  46410. StretchableLayoutManager* layout;
  46411. int itemIndex, mouseDownPos;
  46412. bool isVertical;
  46413. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StretchableLayoutResizerBar);
  46414. };
  46415. #endif // __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  46416. /*** End of inlined file: juce_StretchableLayoutResizerBar.h ***/
  46417. #endif
  46418. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  46419. /*** Start of inlined file: juce_StretchableObjectResizer.h ***/
  46420. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  46421. #define __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  46422. /**
  46423. A utility class for fitting a set of objects whose sizes can vary between
  46424. a minimum and maximum size, into a space.
  46425. This is a trickier algorithm than it would first seem, so I've put it in this
  46426. class to allow it to be shared by various bits of code.
  46427. To use it, create one of these objects, call addItem() to add the list of items
  46428. you need, then call resizeToFit(), which will change all their sizes. You can
  46429. then retrieve the new sizes with getItemSize() and getNumItems().
  46430. It's currently used by the TableHeaderComponent for stretching out the table
  46431. headings to fill the table's width.
  46432. */
  46433. class StretchableObjectResizer
  46434. {
  46435. public:
  46436. /** Creates an empty object resizer. */
  46437. StretchableObjectResizer();
  46438. /** Destructor. */
  46439. ~StretchableObjectResizer();
  46440. /** Adds an item to the list.
  46441. The order parameter lets you specify groups of items that are resized first when some
  46442. space needs to be found. Those items with an order of 0 will be the first ones to be
  46443. resized, and if that doesn't provide enough space to meet the requirements, the algorithm
  46444. will then try resizing the items with an order of 1, then 2, and so on.
  46445. */
  46446. void addItem (double currentSize,
  46447. double minSize,
  46448. double maxSize,
  46449. int order = 0);
  46450. /** Resizes all the items to fit this amount of space.
  46451. This will attempt to fit them in without exceeding each item's miniumum and
  46452. maximum sizes. In cases where none of the items can be expanded or enlarged any
  46453. further, the final size may be greater or less than the size passed in.
  46454. After calling this method, you can retrieve the new sizes with the getItemSize()
  46455. method.
  46456. */
  46457. void resizeToFit (double targetSize);
  46458. /** Returns the number of items that have been added. */
  46459. int getNumItems() const noexcept { return items.size(); }
  46460. /** Returns the size of one of the items. */
  46461. double getItemSize (int index) const noexcept;
  46462. private:
  46463. struct Item
  46464. {
  46465. double size;
  46466. double minSize;
  46467. double maxSize;
  46468. int order;
  46469. };
  46470. OwnedArray <Item> items;
  46471. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StretchableObjectResizer);
  46472. };
  46473. #endif // __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  46474. /*** End of inlined file: juce_StretchableObjectResizer.h ***/
  46475. #endif
  46476. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  46477. #endif
  46478. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  46479. #endif
  46480. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  46481. #endif
  46482. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  46483. /*** Start of inlined file: juce_LookAndFeel.h ***/
  46484. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  46485. #define __JUCE_LOOKANDFEEL_JUCEHEADER__
  46486. class ToggleButton;
  46487. class TextButton;
  46488. class AlertWindow;
  46489. class TextLayout;
  46490. class ScrollBar;
  46491. class BubbleComponent;
  46492. class ComboBox;
  46493. class Button;
  46494. class FilenameComponent;
  46495. class DocumentWindow;
  46496. class ResizableWindow;
  46497. class GroupComponent;
  46498. class MenuBarComponent;
  46499. class DropShadower;
  46500. class GlyphArrangement;
  46501. class PropertyComponent;
  46502. class TableHeaderComponent;
  46503. class Toolbar;
  46504. class ToolbarItemComponent;
  46505. class PopupMenu;
  46506. class ProgressBar;
  46507. class FileBrowserComponent;
  46508. class DirectoryContentsDisplayComponent;
  46509. class FilePreviewComponent;
  46510. class ImageButton;
  46511. class CallOutBox;
  46512. class Drawable;
  46513. class CaretComponent;
  46514. /**
  46515. LookAndFeel objects define the appearance of all the JUCE widgets, and subclasses
  46516. can be used to apply different 'skins' to the application.
  46517. */
  46518. class JUCE_API LookAndFeel
  46519. {
  46520. public:
  46521. /** Creates the default JUCE look and feel. */
  46522. LookAndFeel();
  46523. /** Destructor. */
  46524. virtual ~LookAndFeel();
  46525. /** Returns the current default look-and-feel for a component to use when it
  46526. hasn't got one explicitly set.
  46527. @see setDefaultLookAndFeel
  46528. */
  46529. static LookAndFeel& getDefaultLookAndFeel() noexcept;
  46530. /** Changes the default look-and-feel.
  46531. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  46532. set to null, it will revert to using the default one. The
  46533. object passed-in must be deleted by the caller when
  46534. it's no longer needed.
  46535. @see getDefaultLookAndFeel
  46536. */
  46537. static void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) noexcept;
  46538. /** Looks for a colour that has been registered with the given colour ID number.
  46539. If a colour has been set for this ID number using setColour(), then it is
  46540. returned. If none has been set, it will just return Colours::black.
  46541. The colour IDs for various purposes are stored as enums in the components that
  46542. they are relevent to - for an example, see Slider::ColourIds,
  46543. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  46544. If you're looking up a colour for use in drawing a component, it's usually
  46545. best not to call this directly, but to use the Component::findColour() method
  46546. instead. That will first check whether a suitable colour has been registered
  46547. directly with the component, and will fall-back on calling the component's
  46548. LookAndFeel's findColour() method if none is found.
  46549. @see setColour, Component::findColour, Component::setColour
  46550. */
  46551. const Colour findColour (int colourId) const noexcept;
  46552. /** Registers a colour to be used for a particular purpose.
  46553. For more details, see the comments for findColour().
  46554. @see findColour, Component::findColour, Component::setColour
  46555. */
  46556. void setColour (int colourId, const Colour& colour) noexcept;
  46557. /** Returns true if the specified colour ID has been explicitly set using the
  46558. setColour() method.
  46559. */
  46560. bool isColourSpecified (int colourId) const noexcept;
  46561. virtual const Typeface::Ptr getTypefaceForFont (const Font& font);
  46562. /** Allows you to change the default sans-serif font.
  46563. If you need to supply your own Typeface object for any of the default fonts, rather
  46564. than just supplying the name (e.g. if you want to use an embedded font), then
  46565. you should instead override getTypefaceForFont() to create and return the typeface.
  46566. */
  46567. void setDefaultSansSerifTypefaceName (const String& newName);
  46568. /** Override this to get the chance to swap a component's mouse cursor for a
  46569. customised one.
  46570. */
  46571. virtual const MouseCursor getMouseCursorFor (Component& component);
  46572. /** Draws the lozenge-shaped background for a standard button. */
  46573. virtual void drawButtonBackground (Graphics& g,
  46574. Button& button,
  46575. const Colour& backgroundColour,
  46576. bool isMouseOverButton,
  46577. bool isButtonDown);
  46578. virtual const Font getFontForTextButton (TextButton& button);
  46579. /** Draws the text for a TextButton. */
  46580. virtual void drawButtonText (Graphics& g,
  46581. TextButton& button,
  46582. bool isMouseOverButton,
  46583. bool isButtonDown);
  46584. /** Draws the contents of a standard ToggleButton. */
  46585. virtual void drawToggleButton (Graphics& g,
  46586. ToggleButton& button,
  46587. bool isMouseOverButton,
  46588. bool isButtonDown);
  46589. virtual void changeToggleButtonWidthToFitText (ToggleButton& button);
  46590. virtual void drawTickBox (Graphics& g,
  46591. Component& component,
  46592. float x, float y, float w, float h,
  46593. bool ticked,
  46594. bool isEnabled,
  46595. bool isMouseOverButton,
  46596. bool isButtonDown);
  46597. /* AlertWindow handling..
  46598. */
  46599. virtual AlertWindow* createAlertWindow (const String& title,
  46600. const String& message,
  46601. const String& button1,
  46602. const String& button2,
  46603. const String& button3,
  46604. AlertWindow::AlertIconType iconType,
  46605. int numButtons,
  46606. Component* associatedComponent);
  46607. virtual void drawAlertBox (Graphics& g,
  46608. AlertWindow& alert,
  46609. const Rectangle<int>& textArea,
  46610. TextLayout& textLayout);
  46611. virtual int getAlertBoxWindowFlags();
  46612. virtual int getAlertWindowButtonHeight();
  46613. virtual const Font getAlertWindowMessageFont();
  46614. virtual const Font getAlertWindowFont();
  46615. void setUsingNativeAlertWindows (bool shouldUseNativeAlerts);
  46616. bool isUsingNativeAlertWindows();
  46617. /** Draws a progress bar.
  46618. If the progress value is less than 0 or greater than 1.0, this should draw a spinning
  46619. bar that fills the whole space (i.e. to say that the app is still busy but the progress
  46620. isn't known). It can use the current time as a basis for playing an animation.
  46621. (Used by progress bars in AlertWindow).
  46622. */
  46623. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  46624. int width, int height,
  46625. double progress, const String& textToShow);
  46626. // Draws a small image that spins to indicate that something's happening..
  46627. // This method should use the current time to animate itself, so just keep
  46628. // repainting it every so often.
  46629. virtual void drawSpinningWaitAnimation (Graphics& g, const Colour& colour,
  46630. int x, int y, int w, int h);
  46631. /** Draws one of the buttons on a scrollbar.
  46632. @param g the context to draw into
  46633. @param scrollbar the bar itself
  46634. @param width the width of the button
  46635. @param height the height of the button
  46636. @param buttonDirection the direction of the button, where 0 = up, 1 = right, 2 = down, 3 = left
  46637. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  46638. @param isMouseOverButton whether the mouse is currently over the button (also true if it's held down)
  46639. @param isButtonDown whether the mouse button's held down
  46640. */
  46641. virtual void drawScrollbarButton (Graphics& g,
  46642. ScrollBar& scrollbar,
  46643. int width, int height,
  46644. int buttonDirection,
  46645. bool isScrollbarVertical,
  46646. bool isMouseOverButton,
  46647. bool isButtonDown);
  46648. /** Draws the thumb area of a scrollbar.
  46649. @param g the context to draw into
  46650. @param scrollbar the bar itself
  46651. @param x the x position of the left edge of the thumb area to draw in
  46652. @param y the y position of the top edge of the thumb area to draw in
  46653. @param width the width of the thumb area to draw in
  46654. @param height the height of the thumb area to draw in
  46655. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  46656. @param thumbStartPosition for vertical bars, the y co-ordinate of the top of the
  46657. thumb, or its x position for horizontal bars
  46658. @param thumbSize for vertical bars, the height of the thumb, or its width for
  46659. horizontal bars. This may be 0 if the thumb shouldn't be drawn.
  46660. @param isMouseOver whether the mouse is over the thumb area, also true if the mouse is
  46661. currently dragging the thumb
  46662. @param isMouseDown whether the mouse is currently dragging the scrollbar
  46663. */
  46664. virtual void drawScrollbar (Graphics& g,
  46665. ScrollBar& scrollbar,
  46666. int x, int y,
  46667. int width, int height,
  46668. bool isScrollbarVertical,
  46669. int thumbStartPosition,
  46670. int thumbSize,
  46671. bool isMouseOver,
  46672. bool isMouseDown);
  46673. /** Returns the component effect to use for a scrollbar */
  46674. virtual ImageEffectFilter* getScrollbarEffect();
  46675. /** Returns the minimum length in pixels to use for a scrollbar thumb. */
  46676. virtual int getMinimumScrollbarThumbSize (ScrollBar& scrollbar);
  46677. /** Returns the default thickness to use for a scrollbar. */
  46678. virtual int getDefaultScrollbarWidth();
  46679. /** Returns the length in pixels to use for a scrollbar button. */
  46680. virtual int getScrollbarButtonSize (ScrollBar& scrollbar);
  46681. /** Returns a tick shape for use in yes/no boxes, etc. */
  46682. virtual const Path getTickShape (float height);
  46683. /** Returns a cross shape for use in yes/no boxes, etc. */
  46684. virtual const Path getCrossShape (float height);
  46685. /** Draws the + or - box in a treeview. */
  46686. virtual void drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool isMouseOver);
  46687. virtual void fillTextEditorBackground (Graphics& g, int width, int height, TextEditor& textEditor);
  46688. virtual void drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor);
  46689. virtual CaretComponent* createCaretComponent (Component* keyFocusOwner);
  46690. // These return a pointer to an internally cached drawable - make sure you don't keep
  46691. // a copy of this pointer anywhere, as it may become invalid in the future.
  46692. virtual const Drawable* getDefaultFolderImage();
  46693. virtual const Drawable* getDefaultDocumentFileImage();
  46694. virtual void createFileChooserHeaderText (const String& title,
  46695. const String& instructions,
  46696. GlyphArrangement& destArrangement,
  46697. int width);
  46698. virtual void drawFileBrowserRow (Graphics& g, int width, int height,
  46699. const String& filename, Image* icon,
  46700. const String& fileSizeDescription,
  46701. const String& fileTimeDescription,
  46702. bool isDirectory,
  46703. bool isItemSelected,
  46704. int itemIndex,
  46705. DirectoryContentsDisplayComponent& component);
  46706. virtual Button* createFileBrowserGoUpButton();
  46707. virtual void layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  46708. DirectoryContentsDisplayComponent* fileListComponent,
  46709. FilePreviewComponent* previewComp,
  46710. ComboBox* currentPathBox,
  46711. TextEditor* filenameBox,
  46712. Button* goUpButton);
  46713. virtual void drawBubble (Graphics& g,
  46714. float tipX, float tipY,
  46715. float boxX, float boxY, float boxW, float boxH);
  46716. /** Fills the background of a popup menu component. */
  46717. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  46718. /** Draws one of the items in a popup menu. */
  46719. virtual void drawPopupMenuItem (Graphics& g,
  46720. int width, int height,
  46721. bool isSeparator,
  46722. bool isActive,
  46723. bool isHighlighted,
  46724. bool isTicked,
  46725. bool hasSubMenu,
  46726. const String& text,
  46727. const String& shortcutKeyText,
  46728. Image* image,
  46729. const Colour* const textColour);
  46730. /** Returns the size and style of font to use in popup menus. */
  46731. virtual const Font getPopupMenuFont();
  46732. virtual void drawPopupMenuUpDownArrow (Graphics& g,
  46733. int width, int height,
  46734. bool isScrollUpArrow);
  46735. /** Finds the best size for an item in a popup menu. */
  46736. virtual void getIdealPopupMenuItemSize (const String& text,
  46737. bool isSeparator,
  46738. int standardMenuItemHeight,
  46739. int& idealWidth,
  46740. int& idealHeight);
  46741. virtual int getMenuWindowFlags();
  46742. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  46743. bool isMouseOverBar,
  46744. MenuBarComponent& menuBar);
  46745. virtual int getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  46746. virtual const Font getMenuBarFont (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  46747. virtual void drawMenuBarItem (Graphics& g,
  46748. int width, int height,
  46749. int itemIndex,
  46750. const String& itemText,
  46751. bool isMouseOverItem,
  46752. bool isMenuOpen,
  46753. bool isMouseOverBar,
  46754. MenuBarComponent& menuBar);
  46755. virtual void drawComboBox (Graphics& g, int width, int height,
  46756. bool isButtonDown,
  46757. int buttonX, int buttonY,
  46758. int buttonW, int buttonH,
  46759. ComboBox& box);
  46760. virtual const Font getComboBoxFont (ComboBox& box);
  46761. virtual Label* createComboBoxTextBox (ComboBox& box);
  46762. virtual void positionComboBoxText (ComboBox& box, Label& labelToPosition);
  46763. virtual void drawLabel (Graphics& g, Label& label);
  46764. virtual void drawLinearSlider (Graphics& g,
  46765. int x, int y,
  46766. int width, int height,
  46767. float sliderPos,
  46768. float minSliderPos,
  46769. float maxSliderPos,
  46770. const Slider::SliderStyle style,
  46771. Slider& slider);
  46772. virtual void drawLinearSliderBackground (Graphics& g,
  46773. int x, int y,
  46774. int width, int height,
  46775. float sliderPos,
  46776. float minSliderPos,
  46777. float maxSliderPos,
  46778. const Slider::SliderStyle style,
  46779. Slider& slider);
  46780. virtual void drawLinearSliderThumb (Graphics& g,
  46781. int x, int y,
  46782. int width, int height,
  46783. float sliderPos,
  46784. float minSliderPos,
  46785. float maxSliderPos,
  46786. const Slider::SliderStyle style,
  46787. Slider& slider);
  46788. virtual int getSliderThumbRadius (Slider& slider);
  46789. virtual void drawRotarySlider (Graphics& g,
  46790. int x, int y,
  46791. int width, int height,
  46792. float sliderPosProportional,
  46793. float rotaryStartAngle,
  46794. float rotaryEndAngle,
  46795. Slider& slider);
  46796. virtual Button* createSliderButton (bool isIncrement);
  46797. virtual Label* createSliderTextBox (Slider& slider);
  46798. virtual ImageEffectFilter* getSliderEffect();
  46799. virtual void getTooltipSize (const String& tipText, int& width, int& height);
  46800. virtual void drawTooltip (Graphics& g, const String& text, int width, int height);
  46801. virtual Button* createFilenameComponentBrowseButton (const String& text);
  46802. virtual void layoutFilenameComponent (FilenameComponent& filenameComp,
  46803. ComboBox* filenameBox, Button* browseButton);
  46804. virtual void drawCornerResizer (Graphics& g,
  46805. int w, int h,
  46806. bool isMouseOver,
  46807. bool isMouseDragging);
  46808. virtual void drawResizableFrame (Graphics& g,
  46809. int w, int h,
  46810. const BorderSize<int>& borders);
  46811. virtual void fillResizableWindowBackground (Graphics& g, int w, int h,
  46812. const BorderSize<int>& border,
  46813. ResizableWindow& window);
  46814. virtual void drawResizableWindowBorder (Graphics& g,
  46815. int w, int h,
  46816. const BorderSize<int>& border,
  46817. ResizableWindow& window);
  46818. virtual void drawDocumentWindowTitleBar (DocumentWindow& window,
  46819. Graphics& g, int w, int h,
  46820. int titleSpaceX, int titleSpaceW,
  46821. const Image* icon,
  46822. bool drawTitleTextOnLeft);
  46823. virtual Button* createDocumentWindowButton (int buttonType);
  46824. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  46825. int titleBarX, int titleBarY,
  46826. int titleBarW, int titleBarH,
  46827. Button* minimiseButton,
  46828. Button* maximiseButton,
  46829. Button* closeButton,
  46830. bool positionTitleBarButtonsOnLeft);
  46831. virtual int getDefaultMenuBarHeight();
  46832. virtual DropShadower* createDropShadowerForComponent (Component* component);
  46833. virtual void drawStretchableLayoutResizerBar (Graphics& g,
  46834. int w, int h,
  46835. bool isVerticalBar,
  46836. bool isMouseOver,
  46837. bool isMouseDragging);
  46838. virtual void drawGroupComponentOutline (Graphics& g, int w, int h,
  46839. const String& text,
  46840. const Justification& position,
  46841. GroupComponent& group);
  46842. virtual void createTabButtonShape (Path& p,
  46843. int width, int height,
  46844. int tabIndex,
  46845. const String& text,
  46846. Button& button,
  46847. TabbedButtonBar::Orientation orientation,
  46848. bool isMouseOver,
  46849. bool isMouseDown,
  46850. bool isFrontTab);
  46851. virtual void fillTabButtonShape (Graphics& g,
  46852. const Path& path,
  46853. const Colour& preferredBackgroundColour,
  46854. int tabIndex,
  46855. const String& text,
  46856. Button& button,
  46857. TabbedButtonBar::Orientation orientation,
  46858. bool isMouseOver,
  46859. bool isMouseDown,
  46860. bool isFrontTab);
  46861. virtual void drawTabButtonText (Graphics& g,
  46862. int x, int y, int w, int h,
  46863. const Colour& preferredBackgroundColour,
  46864. int tabIndex,
  46865. const String& text,
  46866. Button& button,
  46867. TabbedButtonBar::Orientation orientation,
  46868. bool isMouseOver,
  46869. bool isMouseDown,
  46870. bool isFrontTab);
  46871. virtual int getTabButtonOverlap (int tabDepth);
  46872. virtual int getTabButtonSpaceAroundImage();
  46873. virtual int getTabButtonBestWidth (int tabIndex,
  46874. const String& text,
  46875. int tabDepth,
  46876. Button& button);
  46877. virtual void drawTabButton (Graphics& g,
  46878. int w, int h,
  46879. const Colour& preferredColour,
  46880. int tabIndex,
  46881. const String& text,
  46882. Button& button,
  46883. TabbedButtonBar::Orientation orientation,
  46884. bool isMouseOver,
  46885. bool isMouseDown,
  46886. bool isFrontTab);
  46887. virtual void drawTabAreaBehindFrontButton (Graphics& g,
  46888. int w, int h,
  46889. TabbedButtonBar& tabBar,
  46890. TabbedButtonBar::Orientation orientation);
  46891. virtual Button* createTabBarExtrasButton();
  46892. virtual void drawImageButton (Graphics& g, Image* image,
  46893. int imageX, int imageY, int imageW, int imageH,
  46894. const Colour& overlayColour,
  46895. float imageOpacity,
  46896. ImageButton& button);
  46897. virtual void drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header);
  46898. virtual void drawTableHeaderColumn (Graphics& g, const String& columnName, int columnId,
  46899. int width, int height,
  46900. bool isMouseOver, bool isMouseDown,
  46901. int columnFlags);
  46902. virtual void paintToolbarBackground (Graphics& g, int width, int height, Toolbar& toolbar);
  46903. virtual Button* createToolbarMissingItemsButton (Toolbar& toolbar);
  46904. virtual void paintToolbarButtonBackground (Graphics& g, int width, int height,
  46905. bool isMouseOver, bool isMouseDown,
  46906. ToolbarItemComponent& component);
  46907. virtual void paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  46908. const String& text, ToolbarItemComponent& component);
  46909. virtual void drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  46910. bool isOpen, int width, int height);
  46911. virtual void drawPropertyComponentBackground (Graphics& g, int width, int height,
  46912. PropertyComponent& component);
  46913. virtual void drawPropertyComponentLabel (Graphics& g, int width, int height,
  46914. PropertyComponent& component);
  46915. virtual const Rectangle<int> getPropertyComponentContentPosition (PropertyComponent& component);
  46916. virtual void drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path);
  46917. virtual void drawLevelMeter (Graphics& g, int width, int height, float level);
  46918. virtual void drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription);
  46919. /** Plays the system's default 'beep' noise, to alert the user about something very important.
  46920. */
  46921. virtual void playAlertSound();
  46922. /** Utility function to draw a shiny, glassy circle (for round LED-type buttons). */
  46923. static void drawGlassSphere (Graphics& g,
  46924. float x, float y,
  46925. float diameter,
  46926. const Colour& colour,
  46927. float outlineThickness) noexcept;
  46928. static void drawGlassPointer (Graphics& g,
  46929. float x, float y,
  46930. float diameter,
  46931. const Colour& colour, float outlineThickness,
  46932. int direction) noexcept;
  46933. /** Utility function to draw a shiny, glassy oblong (for text buttons). */
  46934. static void drawGlassLozenge (Graphics& g,
  46935. float x, float y,
  46936. float width, float height,
  46937. const Colour& colour,
  46938. float outlineThickness,
  46939. float cornerSize,
  46940. bool flatOnLeft, bool flatOnRight,
  46941. bool flatOnTop, bool flatOnBottom) noexcept;
  46942. static Drawable* loadDrawableFromData (const void* data, size_t numBytes);
  46943. private:
  46944. friend class WeakReference<LookAndFeel>;
  46945. WeakReference<LookAndFeel>::Master weakReferenceMaster;
  46946. const WeakReference<LookAndFeel>::SharedRef& getWeakReference();
  46947. Array <int> colourIds;
  46948. Array <Colour> colours;
  46949. // default typeface names
  46950. String defaultSans, defaultSerif, defaultFixed;
  46951. ScopedPointer<Drawable> folderImage, documentImage;
  46952. bool useNativeAlertWindows;
  46953. void drawShinyButtonShape (Graphics& g,
  46954. float x, float y, float w, float h, float maxCornerSize,
  46955. const Colour& baseColour,
  46956. float strokeWidth,
  46957. bool flatOnLeft,
  46958. bool flatOnRight,
  46959. bool flatOnTop,
  46960. bool flatOnBottom) noexcept;
  46961. // This has been deprecated - see the new parameter list..
  46962. virtual int drawFileBrowserRow (Graphics&, int, int, const String&, Image*, const String&, const String&, bool, bool, int) { return 0; }
  46963. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LookAndFeel);
  46964. };
  46965. #endif // __JUCE_LOOKANDFEEL_JUCEHEADER__
  46966. /*** End of inlined file: juce_LookAndFeel.h ***/
  46967. #endif
  46968. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  46969. /*** Start of inlined file: juce_OldSchoolLookAndFeel.h ***/
  46970. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  46971. #define __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  46972. /**
  46973. The original Juce look-and-feel.
  46974. */
  46975. class JUCE_API OldSchoolLookAndFeel : public LookAndFeel
  46976. {
  46977. public:
  46978. /** Creates the default JUCE look and feel. */
  46979. OldSchoolLookAndFeel();
  46980. /** Destructor. */
  46981. virtual ~OldSchoolLookAndFeel();
  46982. /** Draws the lozenge-shaped background for a standard button. */
  46983. virtual void drawButtonBackground (Graphics& g,
  46984. Button& button,
  46985. const Colour& backgroundColour,
  46986. bool isMouseOverButton,
  46987. bool isButtonDown);
  46988. /** Draws the contents of a standard ToggleButton. */
  46989. virtual void drawToggleButton (Graphics& g,
  46990. ToggleButton& button,
  46991. bool isMouseOverButton,
  46992. bool isButtonDown);
  46993. virtual void drawTickBox (Graphics& g,
  46994. Component& component,
  46995. float x, float y, float w, float h,
  46996. bool ticked,
  46997. bool isEnabled,
  46998. bool isMouseOverButton,
  46999. bool isButtonDown);
  47000. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  47001. int width, int height,
  47002. double progress, const String& textToShow);
  47003. virtual void drawScrollbarButton (Graphics& g,
  47004. ScrollBar& scrollbar,
  47005. int width, int height,
  47006. int buttonDirection,
  47007. bool isScrollbarVertical,
  47008. bool isMouseOverButton,
  47009. bool isButtonDown);
  47010. virtual void drawScrollbar (Graphics& g,
  47011. ScrollBar& scrollbar,
  47012. int x, int y,
  47013. int width, int height,
  47014. bool isScrollbarVertical,
  47015. int thumbStartPosition,
  47016. int thumbSize,
  47017. bool isMouseOver,
  47018. bool isMouseDown);
  47019. virtual ImageEffectFilter* getScrollbarEffect();
  47020. virtual void drawTextEditorOutline (Graphics& g,
  47021. int width, int height,
  47022. TextEditor& textEditor);
  47023. /** Fills the background of a popup menu component. */
  47024. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  47025. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  47026. bool isMouseOverBar,
  47027. MenuBarComponent& menuBar);
  47028. virtual void drawComboBox (Graphics& g, int width, int height,
  47029. bool isButtonDown,
  47030. int buttonX, int buttonY,
  47031. int buttonW, int buttonH,
  47032. ComboBox& box);
  47033. virtual const Font getComboBoxFont (ComboBox& box);
  47034. virtual void drawLinearSlider (Graphics& g,
  47035. int x, int y,
  47036. int width, int height,
  47037. float sliderPos,
  47038. float minSliderPos,
  47039. float maxSliderPos,
  47040. const Slider::SliderStyle style,
  47041. Slider& slider);
  47042. virtual int getSliderThumbRadius (Slider& slider);
  47043. virtual Button* createSliderButton (bool isIncrement);
  47044. virtual ImageEffectFilter* getSliderEffect();
  47045. virtual void drawCornerResizer (Graphics& g,
  47046. int w, int h,
  47047. bool isMouseOver,
  47048. bool isMouseDragging);
  47049. virtual Button* createDocumentWindowButton (int buttonType);
  47050. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  47051. int titleBarX, int titleBarY,
  47052. int titleBarW, int titleBarH,
  47053. Button* minimiseButton,
  47054. Button* maximiseButton,
  47055. Button* closeButton,
  47056. bool positionTitleBarButtonsOnLeft);
  47057. private:
  47058. DropShadowEffect scrollbarShadow;
  47059. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OldSchoolLookAndFeel);
  47060. };
  47061. #endif // __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  47062. /*** End of inlined file: juce_OldSchoolLookAndFeel.h ***/
  47063. #endif
  47064. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  47065. /*** Start of inlined file: juce_MenuBarComponent.h ***/
  47066. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  47067. #define __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  47068. /**
  47069. A menu bar component.
  47070. @see MenuBarModel
  47071. */
  47072. class JUCE_API MenuBarComponent : public Component,
  47073. private MenuBarModel::Listener,
  47074. private Timer
  47075. {
  47076. public:
  47077. /** Creates a menu bar.
  47078. @param model the model object to use to control this bar. You can
  47079. pass 0 into this if you like, and set the model later
  47080. using the setModel() method
  47081. */
  47082. MenuBarComponent (MenuBarModel* model);
  47083. /** Destructor. */
  47084. ~MenuBarComponent();
  47085. /** Changes the model object to use to control the bar.
  47086. This can be a null pointer, in which case the bar will be empty. Don't delete the object
  47087. that is passed-in while it's still being used by this MenuBar.
  47088. */
  47089. void setModel (MenuBarModel* newModel);
  47090. /** Returns the current menu bar model being used.
  47091. */
  47092. MenuBarModel* getModel() const noexcept;
  47093. /** Pops up one of the menu items.
  47094. This lets you manually open one of the menus - it could be triggered by a
  47095. key shortcut, for example.
  47096. */
  47097. void showMenu (int menuIndex);
  47098. /** @internal */
  47099. void paint (Graphics& g);
  47100. /** @internal */
  47101. void resized();
  47102. /** @internal */
  47103. void mouseEnter (const MouseEvent& e);
  47104. /** @internal */
  47105. void mouseExit (const MouseEvent& e);
  47106. /** @internal */
  47107. void mouseDown (const MouseEvent& e);
  47108. /** @internal */
  47109. void mouseDrag (const MouseEvent& e);
  47110. /** @internal */
  47111. void mouseUp (const MouseEvent& e);
  47112. /** @internal */
  47113. void mouseMove (const MouseEvent& e);
  47114. /** @internal */
  47115. void handleCommandMessage (int commandId);
  47116. /** @internal */
  47117. bool keyPressed (const KeyPress& key);
  47118. /** @internal */
  47119. void menuBarItemsChanged (MenuBarModel* menuBarModel);
  47120. /** @internal */
  47121. void menuCommandInvoked (MenuBarModel* menuBarModel,
  47122. const ApplicationCommandTarget::InvocationInfo& info);
  47123. private:
  47124. MenuBarModel* model;
  47125. StringArray menuNames;
  47126. Array <int> xPositions;
  47127. int itemUnderMouse, currentPopupIndex, topLevelIndexClicked;
  47128. int lastMouseX, lastMouseY;
  47129. int getItemAt (int x, int y);
  47130. void setItemUnderMouse (int index);
  47131. void setOpenItem (int index);
  47132. void updateItemUnderMouse (int x, int y);
  47133. void timerCallback();
  47134. void repaintMenuItem (int index);
  47135. void menuDismissed (int topLevelIndex, int itemId);
  47136. static void menuBarMenuDismissedCallback (int, MenuBarComponent*, int);
  47137. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuBarComponent);
  47138. };
  47139. #endif // __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  47140. /*** End of inlined file: juce_MenuBarComponent.h ***/
  47141. #endif
  47142. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  47143. #endif
  47144. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  47145. #endif
  47146. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  47147. #endif
  47148. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  47149. #endif
  47150. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  47151. #endif
  47152. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  47153. #endif
  47154. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  47155. /*** Start of inlined file: juce_LassoComponent.h ***/
  47156. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  47157. #define __JUCE_LASSOCOMPONENT_JUCEHEADER__
  47158. /*** Start of inlined file: juce_SelectedItemSet.h ***/
  47159. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  47160. #define __JUCE_SELECTEDITEMSET_JUCEHEADER__
  47161. /** Manages a list of selectable items.
  47162. Use one of these to keep a track of things that the user has highlighted, like
  47163. icons or things in a list.
  47164. The class is templated so that you can use it to hold either a set of pointers
  47165. to objects, or a set of ID numbers or handles, for cases where each item may
  47166. not always have a corresponding object.
  47167. To be informed when items are selected/deselected, register a ChangeListener with
  47168. this object.
  47169. @see SelectableObject
  47170. */
  47171. template <class SelectableItemType>
  47172. class JUCE_API SelectedItemSet : public ChangeBroadcaster
  47173. {
  47174. public:
  47175. typedef SelectableItemType ItemType;
  47176. typedef PARAMETER_TYPE (SelectableItemType) ParameterType;
  47177. /** Creates an empty set. */
  47178. SelectedItemSet()
  47179. {
  47180. }
  47181. /** Creates a set based on an array of items. */
  47182. explicit SelectedItemSet (const Array <SelectableItemType>& items)
  47183. : selectedItems (items)
  47184. {
  47185. }
  47186. /** Creates a copy of another set. */
  47187. SelectedItemSet (const SelectedItemSet& other)
  47188. : selectedItems (other.selectedItems)
  47189. {
  47190. }
  47191. /** Creates a copy of another set. */
  47192. SelectedItemSet& operator= (const SelectedItemSet& other)
  47193. {
  47194. if (selectedItems != other.selectedItems)
  47195. {
  47196. selectedItems = other.selectedItems;
  47197. changed();
  47198. }
  47199. return *this;
  47200. }
  47201. /** Clears any other currently selected items, and selects this item.
  47202. If this item is already the only thing selected, no change notification
  47203. will be sent out.
  47204. @see addToSelection, addToSelectionBasedOnModifiers
  47205. */
  47206. void selectOnly (ParameterType item)
  47207. {
  47208. if (isSelected (item))
  47209. {
  47210. for (int i = selectedItems.size(); --i >= 0;)
  47211. {
  47212. if (selectedItems.getUnchecked(i) != item)
  47213. {
  47214. deselect (selectedItems.getUnchecked(i));
  47215. i = jmin (i, selectedItems.size());
  47216. }
  47217. }
  47218. }
  47219. else
  47220. {
  47221. deselectAll();
  47222. changed();
  47223. selectedItems.add (item);
  47224. itemSelected (item);
  47225. }
  47226. }
  47227. /** Selects an item.
  47228. If the item is already selected, no change notification will be sent out.
  47229. @see selectOnly, addToSelectionBasedOnModifiers
  47230. */
  47231. void addToSelection (ParameterType item)
  47232. {
  47233. if (! isSelected (item))
  47234. {
  47235. changed();
  47236. selectedItems.add (item);
  47237. itemSelected (item);
  47238. }
  47239. }
  47240. /** Selects or deselects an item.
  47241. This will use the modifier keys to decide whether to deselect other items
  47242. first.
  47243. So if the shift key is held down, the item will be added without deselecting
  47244. anything (same as calling addToSelection() )
  47245. If no modifiers are down, the current selection will be cleared first (same
  47246. as calling selectOnly() )
  47247. If the ctrl (or command on the Mac) key is held down, the item will be toggled -
  47248. so it'll be added to the set unless it's already there, in which case it'll be
  47249. deselected.
  47250. If the items that you're selecting can also be dragged, you may need to use the
  47251. addToSelectionOnMouseDown() and addToSelectionOnMouseUp() calls to handle the
  47252. subtleties of this kind of usage.
  47253. @see selectOnly, addToSelection, addToSelectionOnMouseDown, addToSelectionOnMouseUp
  47254. */
  47255. void addToSelectionBasedOnModifiers (ParameterType item,
  47256. const ModifierKeys& modifiers)
  47257. {
  47258. if (modifiers.isShiftDown())
  47259. {
  47260. addToSelection (item);
  47261. }
  47262. else if (modifiers.isCommandDown())
  47263. {
  47264. if (isSelected (item))
  47265. deselect (item);
  47266. else
  47267. addToSelection (item);
  47268. }
  47269. else
  47270. {
  47271. selectOnly (item);
  47272. }
  47273. }
  47274. /** Selects or deselects items that can also be dragged, based on a mouse-down event.
  47275. If you call addToSelectionOnMouseDown() at the start of your mouseDown event,
  47276. and then call addToSelectionOnMouseUp() at the end of your mouseUp event, this
  47277. makes it easy to handle multiple-selection of sets of objects that can also
  47278. be dragged.
  47279. For example, if you have several items already selected, and you click on
  47280. one of them (without dragging), then you'd expect this to deselect the other, and
  47281. just select the item you clicked on. But if you had clicked on this item and
  47282. dragged it, you'd have expected them all to stay selected.
  47283. When you call this method, you'll need to store the boolean result, because the
  47284. addToSelectionOnMouseUp() method will need to be know this value.
  47285. @see addToSelectionOnMouseUp, addToSelectionBasedOnModifiers
  47286. */
  47287. bool addToSelectionOnMouseDown (ParameterType item,
  47288. const ModifierKeys& modifiers)
  47289. {
  47290. if (isSelected (item))
  47291. {
  47292. return ! modifiers.isPopupMenu();
  47293. }
  47294. else
  47295. {
  47296. addToSelectionBasedOnModifiers (item, modifiers);
  47297. return false;
  47298. }
  47299. }
  47300. /** Selects or deselects items that can also be dragged, based on a mouse-up event.
  47301. Call this during a mouseUp callback, when you have previously called the
  47302. addToSelectionOnMouseDown() method during your mouseDown event.
  47303. See addToSelectionOnMouseDown() for more info
  47304. @param item the item to select (or deselect)
  47305. @param modifiers the modifiers from the mouse-up event
  47306. @param wasItemDragged true if your item was dragged during the mouse click
  47307. @param resultOfMouseDownSelectMethod this is the boolean return value that came
  47308. back from the addToSelectionOnMouseDown() call that you
  47309. should have made during the matching mouseDown event
  47310. */
  47311. void addToSelectionOnMouseUp (ParameterType item,
  47312. const ModifierKeys& modifiers,
  47313. const bool wasItemDragged,
  47314. const bool resultOfMouseDownSelectMethod)
  47315. {
  47316. if (resultOfMouseDownSelectMethod && ! wasItemDragged)
  47317. addToSelectionBasedOnModifiers (item, modifiers);
  47318. }
  47319. /** Deselects an item. */
  47320. void deselect (ParameterType item)
  47321. {
  47322. const int i = selectedItems.indexOf (item);
  47323. if (i >= 0)
  47324. {
  47325. changed();
  47326. itemDeselected (selectedItems.remove (i));
  47327. }
  47328. }
  47329. /** Deselects all items. */
  47330. void deselectAll()
  47331. {
  47332. if (selectedItems.size() > 0)
  47333. {
  47334. changed();
  47335. for (int i = selectedItems.size(); --i >= 0;)
  47336. {
  47337. itemDeselected (selectedItems.remove (i));
  47338. i = jmin (i, selectedItems.size());
  47339. }
  47340. }
  47341. }
  47342. /** Returns the number of currently selected items.
  47343. @see getSelectedItem
  47344. */
  47345. int getNumSelected() const noexcept
  47346. {
  47347. return selectedItems.size();
  47348. }
  47349. /** Returns one of the currently selected items.
  47350. Returns 0 if the index is out-of-range.
  47351. @see getNumSelected
  47352. */
  47353. SelectableItemType getSelectedItem (const int index) const noexcept
  47354. {
  47355. return selectedItems [index];
  47356. }
  47357. /** True if this item is currently selected. */
  47358. bool isSelected (ParameterType item) const noexcept
  47359. {
  47360. return selectedItems.contains (item);
  47361. }
  47362. const Array <SelectableItemType>& getItemArray() const noexcept { return selectedItems; }
  47363. /** Can be overridden to do special handling when an item is selected.
  47364. For example, if the item is an object, you might want to call it and tell
  47365. it that it's being selected.
  47366. */
  47367. virtual void itemSelected (SelectableItemType item) { (void) item; }
  47368. /** Can be overridden to do special handling when an item is deselected.
  47369. For example, if the item is an object, you might want to call it and tell
  47370. it that it's being deselected.
  47371. */
  47372. virtual void itemDeselected (SelectableItemType item) { (void) item; }
  47373. /** Used internally, but can be called to force a change message to be sent to the ChangeListeners.
  47374. */
  47375. void changed (const bool synchronous = false)
  47376. {
  47377. if (synchronous)
  47378. sendSynchronousChangeMessage();
  47379. else
  47380. sendChangeMessage();
  47381. }
  47382. private:
  47383. Array <SelectableItemType> selectedItems;
  47384. JUCE_LEAK_DETECTOR (SelectedItemSet <SelectableItemType>);
  47385. };
  47386. #endif // __JUCE_SELECTEDITEMSET_JUCEHEADER__
  47387. /*** End of inlined file: juce_SelectedItemSet.h ***/
  47388. /**
  47389. A class used by the LassoComponent to manage the things that it selects.
  47390. This allows the LassoComponent to find out which items are within the lasso,
  47391. and to change the list of selected items.
  47392. @see LassoComponent, SelectedItemSet
  47393. */
  47394. template <class SelectableItemType>
  47395. class LassoSource
  47396. {
  47397. public:
  47398. /** Destructor. */
  47399. virtual ~LassoSource() {}
  47400. /** Returns the set of items that lie within a given lassoable region.
  47401. Your implementation of this method must find all the relevent items that lie
  47402. within the given rectangle. and add them to the itemsFound array.
  47403. The co-ordinates are relative to the top-left of the lasso component's parent
  47404. component. (i.e. they are the same as the size and position of the lasso
  47405. component itself).
  47406. */
  47407. virtual void findLassoItemsInArea (Array <SelectableItemType>& itemsFound,
  47408. const Rectangle<int>& area) = 0;
  47409. /** Returns the SelectedItemSet that the lasso should update.
  47410. This set will be continuously updated by the LassoComponent as it gets
  47411. dragged around, so make sure that you've got a ChangeListener attached to
  47412. the set so that your UI objects will know when the selection changes and
  47413. be able to update themselves appropriately.
  47414. */
  47415. virtual SelectedItemSet <SelectableItemType>& getLassoSelection() = 0;
  47416. };
  47417. /**
  47418. A component that acts as a rectangular selection region, which you drag with
  47419. the mouse to select groups of objects (in conjunction with a SelectedItemSet).
  47420. To use one of these:
  47421. - In your mouseDown or mouseDrag event, add the LassoComponent to your parent
  47422. component, and call its beginLasso() method, giving it a
  47423. suitable LassoSource object that it can use to find out which items are in
  47424. the active area.
  47425. - Each time your parent component gets a mouseDrag event, call dragLasso()
  47426. to update the lasso's position - it will use its LassoSource to calculate and
  47427. update the current selection.
  47428. - After the drag has finished and you get a mouseUp callback, you should call
  47429. endLasso() to clean up. This will make the lasso component invisible, and you
  47430. can remove it from the parent component, or delete it.
  47431. The class takes into account the modifier keys that are being held down while
  47432. the lasso is being dragged, so if shift is pressed, then any lassoed items will
  47433. be added to the original selection; if ctrl or command is pressed, they will be
  47434. xor'ed with any previously selected items.
  47435. @see LassoSource, SelectedItemSet
  47436. */
  47437. template <class SelectableItemType>
  47438. class LassoComponent : public Component
  47439. {
  47440. public:
  47441. /** Creates a Lasso component.
  47442. The fill colour is used to fill the lasso'ed rectangle, and the outline
  47443. colour is used to draw a line around its edge.
  47444. */
  47445. explicit LassoComponent (const int outlineThickness_ = 1)
  47446. : source (nullptr),
  47447. outlineThickness (outlineThickness_)
  47448. {
  47449. }
  47450. /** Destructor. */
  47451. ~LassoComponent()
  47452. {
  47453. }
  47454. /** Call this in your mouseDown event, to initialise a drag.
  47455. Pass in a suitable LassoSource object which the lasso will use to find
  47456. the items and change the selection.
  47457. After using this method to initialise the lasso, repeatedly call dragLasso()
  47458. in your component's mouseDrag callback.
  47459. @see dragLasso, endLasso, LassoSource
  47460. */
  47461. void beginLasso (const MouseEvent& e,
  47462. LassoSource <SelectableItemType>* const lassoSource)
  47463. {
  47464. jassert (source == nullptr); // this suggests that you didn't call endLasso() after the last drag...
  47465. jassert (lassoSource != nullptr); // the source can't be null!
  47466. jassert (getParentComponent() != nullptr); // you need to add this to a parent component for it to work!
  47467. source = lassoSource;
  47468. if (lassoSource != nullptr)
  47469. originalSelection = lassoSource->getLassoSelection().getItemArray();
  47470. setSize (0, 0);
  47471. dragStartPos = e.getMouseDownPosition();
  47472. }
  47473. /** Call this in your mouseDrag event, to update the lasso's position.
  47474. This must be repeatedly calling when the mouse is dragged, after you've
  47475. first initialised the lasso with beginLasso().
  47476. This method takes into account the modifier keys that are being held down, so
  47477. if shift is pressed, then the lassoed items will be added to any that were
  47478. previously selected; if ctrl or command is pressed, then they will be xor'ed
  47479. with previously selected items.
  47480. @see beginLasso, endLasso
  47481. */
  47482. void dragLasso (const MouseEvent& e)
  47483. {
  47484. if (source != nullptr)
  47485. {
  47486. setBounds (Rectangle<int> (dragStartPos, e.getPosition()));
  47487. setVisible (true);
  47488. Array <SelectableItemType> itemsInLasso;
  47489. source->findLassoItemsInArea (itemsInLasso, getBounds());
  47490. if (e.mods.isShiftDown())
  47491. {
  47492. itemsInLasso.removeValuesIn (originalSelection); // to avoid duplicates
  47493. itemsInLasso.addArray (originalSelection);
  47494. }
  47495. else if (e.mods.isCommandDown() || e.mods.isAltDown())
  47496. {
  47497. Array <SelectableItemType> originalMinusNew (originalSelection);
  47498. originalMinusNew.removeValuesIn (itemsInLasso);
  47499. itemsInLasso.removeValuesIn (originalSelection);
  47500. itemsInLasso.addArray (originalMinusNew);
  47501. }
  47502. source->getLassoSelection() = SelectedItemSet <SelectableItemType> (itemsInLasso);
  47503. }
  47504. }
  47505. /** Call this in your mouseUp event, after the lasso has been dragged.
  47506. @see beginLasso, dragLasso
  47507. */
  47508. void endLasso()
  47509. {
  47510. source = nullptr;
  47511. originalSelection.clear();
  47512. setVisible (false);
  47513. }
  47514. /** A set of colour IDs to use to change the colour of various aspects of the label.
  47515. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  47516. methods.
  47517. Note that you can also use the constants from TextEditor::ColourIds to change the
  47518. colour of the text editor that is opened when a label is editable.
  47519. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  47520. */
  47521. enum ColourIds
  47522. {
  47523. lassoFillColourId = 0x1000440, /**< The colour to fill the lasso rectangle with. */
  47524. lassoOutlineColourId = 0x1000441, /**< The colour to draw the outline with. */
  47525. };
  47526. /** @internal */
  47527. void paint (Graphics& g)
  47528. {
  47529. g.fillAll (findColour (lassoFillColourId));
  47530. g.setColour (findColour (lassoOutlineColourId));
  47531. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  47532. // this suggests that you've left a lasso comp lying around after the
  47533. // mouse drag has finished.. Be careful to call endLasso() when you get a
  47534. // mouse-up event.
  47535. jassert (isMouseButtonDownAnywhere());
  47536. }
  47537. /** @internal */
  47538. bool hitTest (int, int) { return false; }
  47539. private:
  47540. Array <SelectableItemType> originalSelection;
  47541. LassoSource <SelectableItemType>* source;
  47542. int outlineThickness;
  47543. Point<int> dragStartPos;
  47544. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LassoComponent);
  47545. };
  47546. #endif // __JUCE_LASSOCOMPONENT_JUCEHEADER__
  47547. /*** End of inlined file: juce_LassoComponent.h ***/
  47548. #endif
  47549. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  47550. #endif
  47551. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  47552. #endif
  47553. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  47554. /*** Start of inlined file: juce_MouseInputSource.h ***/
  47555. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  47556. #define __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  47557. class MouseInputSourceInternal;
  47558. /**
  47559. Represents a linear source of mouse events from a mouse device or individual finger
  47560. in a multi-touch environment.
  47561. Each MouseEvent object contains a reference to the MouseInputSource that generated
  47562. it. In an environment with a single mouse for input, all events will come from the
  47563. same source, but in a multi-touch system, there may be multiple MouseInputSource
  47564. obects active, each representing a stream of events coming from a particular finger.
  47565. Events coming from a single MouseInputSource are always sent in a fixed and predictable
  47566. order: a mouseMove will never be called without a mouseEnter having been sent beforehand,
  47567. the only events that can happen between a mouseDown and its corresponding mouseUp are
  47568. mouseDrags, etc.
  47569. When there are multiple touches arriving from multiple MouseInputSources, their
  47570. event streams may arrive in an interleaved order, so you should use the getIndex()
  47571. method to find out which finger each event came from.
  47572. @see MouseEvent
  47573. */
  47574. class JUCE_API MouseInputSource
  47575. {
  47576. public:
  47577. /** Creates a MouseInputSource.
  47578. You should never actually create a MouseInputSource in your own code - the
  47579. library takes care of managing these objects.
  47580. */
  47581. MouseInputSource (int index, bool isMouseDevice);
  47582. /** Destructor. */
  47583. ~MouseInputSource();
  47584. /** Returns true if this object represents a normal desk-based mouse device. */
  47585. bool isMouse() const;
  47586. /** Returns true if this object represents a source of touch events - i.e. a finger or stylus. */
  47587. bool isTouch() const;
  47588. /** Returns true if this source has an on-screen pointer that can hover over
  47589. items without clicking them.
  47590. */
  47591. bool canHover() const;
  47592. /** Returns true if this source may have a scroll wheel. */
  47593. bool hasMouseWheel() const;
  47594. /** Returns this source's index in the global list of possible sources.
  47595. If the system only has a single mouse, there will only be a single MouseInputSource
  47596. with an index of 0.
  47597. If the system supports multi-touch input, then the index will represent a finger
  47598. number, starting from 0. When the first touch event begins, it will have finger
  47599. number 0, and then if a second touch happens while the first is still down, it
  47600. will have index 1, etc.
  47601. */
  47602. int getIndex() const;
  47603. /** Returns true if this device is currently being pressed. */
  47604. bool isDragging() const;
  47605. /** Returns the last-known screen position of this source. */
  47606. const Point<int> getScreenPosition() const;
  47607. /** Returns a set of modifiers that indicate which buttons are currently
  47608. held down on this device.
  47609. */
  47610. const ModifierKeys getCurrentModifiers() const;
  47611. /** Returns the component that was last known to be under this pointer. */
  47612. Component* getComponentUnderMouse() const;
  47613. /** Tells the device to dispatch a mouse-move or mouse-drag event.
  47614. This is asynchronous - the event will occur on the message thread.
  47615. */
  47616. void triggerFakeMove() const;
  47617. /** Returns the number of clicks that should be counted as belonging to the
  47618. current mouse event.
  47619. So the mouse is currently down and it's the second click of a double-click, this
  47620. will return 2.
  47621. */
  47622. int getNumberOfMultipleClicks() const noexcept;
  47623. /** Returns the time at which the last mouse-down occurred. */
  47624. Time getLastMouseDownTime() const noexcept;
  47625. /** Returns the screen position at which the last mouse-down occurred. */
  47626. Point<int> getLastMouseDownPosition() const noexcept;
  47627. /** Returns true if this mouse is currently down, and if it has been dragged more
  47628. than a couple of pixels from the place it was pressed.
  47629. */
  47630. bool hasMouseMovedSignificantlySincePressed() const noexcept;
  47631. /** Returns true if this input source uses a visible mouse cursor. */
  47632. bool hasMouseCursor() const noexcept;
  47633. /** Changes the mouse cursor, (if there is one). */
  47634. void showMouseCursor (const MouseCursor& cursor);
  47635. /** Hides the mouse cursor (if there is one). */
  47636. void hideCursor();
  47637. /** Un-hides the mouse cursor if it was hidden by hideCursor(). */
  47638. void revealCursor();
  47639. /** Forces an update of the mouse cursor for whatever component it's currently over. */
  47640. void forceMouseCursorUpdate();
  47641. /** Returns true if this mouse can be moved indefinitely in any direction without running out of space. */
  47642. bool canDoUnboundedMovement() const noexcept;
  47643. /** Allows the mouse to move beyond the edges of the screen.
  47644. Calling this method when the mouse button is currently pressed will remove the cursor
  47645. from the screen and allow the mouse to (seem to) move beyond the edges of the screen.
  47646. This means that the co-ordinates returned to mouseDrag() will be unbounded, and this
  47647. can be used for things like custom slider controls or dragging objects around, where
  47648. movement would be otherwise be limited by the mouse hitting the edges of the screen.
  47649. The unbounded mode is automatically turned off when the mouse button is released, or
  47650. it can be turned off explicitly by calling this method again.
  47651. @param isEnabled whether to turn this mode on or off
  47652. @param keepCursorVisibleUntilOffscreen if set to false, the cursor will immediately be
  47653. hidden; if true, it will only be hidden when it
  47654. is moved beyond the edge of the screen
  47655. */
  47656. void enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen = false);
  47657. /** @internal */
  47658. void handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, const ModifierKeys& mods);
  47659. /** @internal */
  47660. void handleWheel (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  47661. private:
  47662. friend class Desktop;
  47663. friend class ComponentPeer;
  47664. friend class MouseInputSourceInternal;
  47665. ScopedPointer<MouseInputSourceInternal> pimpl;
  47666. static const Point<int> getCurrentMousePosition();
  47667. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MouseInputSource);
  47668. };
  47669. #endif // __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  47670. /*** End of inlined file: juce_MouseInputSource.h ***/
  47671. #endif
  47672. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  47673. #endif
  47674. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  47675. #endif
  47676. #ifndef __JUCE_MARKERLIST_JUCEHEADER__
  47677. #endif
  47678. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  47679. #endif
  47680. #ifndef __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  47681. #endif
  47682. #ifndef __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  47683. /*** Start of inlined file: juce_RelativeParallelogram.h ***/
  47684. #ifndef __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  47685. #define __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  47686. /**
  47687. A parallelogram defined by three RelativePoint positions.
  47688. @see RelativePoint, RelativeCoordinate
  47689. */
  47690. class JUCE_API RelativeParallelogram
  47691. {
  47692. public:
  47693. RelativeParallelogram();
  47694. RelativeParallelogram (const Rectangle<float>& simpleRectangle);
  47695. RelativeParallelogram (const RelativePoint& topLeft, const RelativePoint& topRight, const RelativePoint& bottomLeft);
  47696. RelativeParallelogram (const String& topLeft, const String& topRight, const String& bottomLeft);
  47697. ~RelativeParallelogram();
  47698. void resolveThreePoints (Point<float>* points, Expression::Scope* scope) const;
  47699. void resolveFourCorners (Point<float>* points, Expression::Scope* scope) const;
  47700. const Rectangle<float> getBounds (Expression::Scope* scope) const;
  47701. void getPath (Path& path, Expression::Scope* scope) const;
  47702. const AffineTransform resetToPerpendicular (Expression::Scope* scope);
  47703. bool isDynamic() const;
  47704. bool operator== (const RelativeParallelogram& other) const noexcept;
  47705. bool operator!= (const RelativeParallelogram& other) const noexcept;
  47706. static const Point<float> getInternalCoordForPoint (const Point<float>* parallelogramCorners, Point<float> point) noexcept;
  47707. static const Point<float> getPointForInternalCoord (const Point<float>* parallelogramCorners, const Point<float>& internalPoint) noexcept;
  47708. static const Rectangle<float> getBoundingBox (const Point<float>* parallelogramCorners) noexcept;
  47709. RelativePoint topLeft, topRight, bottomLeft;
  47710. };
  47711. #endif // __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  47712. /*** End of inlined file: juce_RelativeParallelogram.h ***/
  47713. #endif
  47714. #ifndef __JUCE_RELATIVEPOINT_JUCEHEADER__
  47715. #endif
  47716. #ifndef __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  47717. /*** Start of inlined file: juce_RelativePointPath.h ***/
  47718. #ifndef __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  47719. #define __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  47720. class DrawablePath;
  47721. /**
  47722. A path object that consists of RelativePoint coordinates rather than the normal fixed ones.
  47723. One of these paths can be converted into a Path object for drawing and manipulation, but
  47724. unlike a Path, its points can be dynamic instead of just fixed.
  47725. @see RelativePoint, RelativeCoordinate
  47726. */
  47727. class JUCE_API RelativePointPath
  47728. {
  47729. public:
  47730. RelativePointPath();
  47731. RelativePointPath (const RelativePointPath& other);
  47732. explicit RelativePointPath (const Path& path);
  47733. ~RelativePointPath();
  47734. bool operator== (const RelativePointPath& other) const noexcept;
  47735. bool operator!= (const RelativePointPath& other) const noexcept;
  47736. /** Resolves this points in this path and adds them to a normal Path object. */
  47737. void createPath (Path& path, Expression::Scope* scope) const;
  47738. /** Returns true if the path contains any non-fixed points. */
  47739. bool containsAnyDynamicPoints() const;
  47740. /** Quickly swaps the contents of this path with another. */
  47741. void swapWith (RelativePointPath& other) noexcept;
  47742. /** The types of element that may be contained in this path.
  47743. @see RelativePointPath::ElementBase
  47744. */
  47745. enum ElementType
  47746. {
  47747. nullElement,
  47748. startSubPathElement,
  47749. closeSubPathElement,
  47750. lineToElement,
  47751. quadraticToElement,
  47752. cubicToElement
  47753. };
  47754. /** Base class for the elements that make up a RelativePointPath.
  47755. */
  47756. class JUCE_API ElementBase
  47757. {
  47758. public:
  47759. ElementBase (ElementType type);
  47760. virtual ~ElementBase() {}
  47761. virtual ValueTree createTree() const = 0;
  47762. virtual void addToPath (Path& path, Expression::Scope*) const = 0;
  47763. virtual RelativePoint* getControlPoints (int& numPoints) = 0;
  47764. virtual ElementBase* clone() const = 0;
  47765. bool isDynamic();
  47766. const ElementType type;
  47767. private:
  47768. JUCE_DECLARE_NON_COPYABLE (ElementBase);
  47769. };
  47770. class JUCE_API StartSubPath : public ElementBase
  47771. {
  47772. public:
  47773. StartSubPath (const RelativePoint& pos);
  47774. ValueTree createTree() const;
  47775. void addToPath (Path& path, Expression::Scope*) const;
  47776. RelativePoint* getControlPoints (int& numPoints);
  47777. ElementBase* clone() const;
  47778. RelativePoint startPos;
  47779. private:
  47780. JUCE_DECLARE_NON_COPYABLE (StartSubPath);
  47781. };
  47782. class JUCE_API CloseSubPath : public ElementBase
  47783. {
  47784. public:
  47785. CloseSubPath();
  47786. ValueTree createTree() const;
  47787. void addToPath (Path& path, Expression::Scope*) const;
  47788. RelativePoint* getControlPoints (int& numPoints);
  47789. ElementBase* clone() const;
  47790. private:
  47791. JUCE_DECLARE_NON_COPYABLE (CloseSubPath);
  47792. };
  47793. class JUCE_API LineTo : public ElementBase
  47794. {
  47795. public:
  47796. LineTo (const RelativePoint& endPoint);
  47797. ValueTree createTree() const;
  47798. void addToPath (Path& path, Expression::Scope*) const;
  47799. RelativePoint* getControlPoints (int& numPoints);
  47800. ElementBase* clone() const;
  47801. RelativePoint endPoint;
  47802. private:
  47803. JUCE_DECLARE_NON_COPYABLE (LineTo);
  47804. };
  47805. class JUCE_API QuadraticTo : public ElementBase
  47806. {
  47807. public:
  47808. QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint);
  47809. ValueTree createTree() const;
  47810. void addToPath (Path& path, Expression::Scope*) const;
  47811. RelativePoint* getControlPoints (int& numPoints);
  47812. ElementBase* clone() const;
  47813. RelativePoint controlPoints[2];
  47814. private:
  47815. JUCE_DECLARE_NON_COPYABLE (QuadraticTo);
  47816. };
  47817. class JUCE_API CubicTo : public ElementBase
  47818. {
  47819. public:
  47820. CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint);
  47821. ValueTree createTree() const;
  47822. void addToPath (Path& path, Expression::Scope*) const;
  47823. RelativePoint* getControlPoints (int& numPoints);
  47824. ElementBase* clone() const;
  47825. RelativePoint controlPoints[3];
  47826. private:
  47827. JUCE_DECLARE_NON_COPYABLE (CubicTo);
  47828. };
  47829. void addElement (ElementBase* newElement);
  47830. OwnedArray <ElementBase> elements;
  47831. bool usesNonZeroWinding;
  47832. private:
  47833. class Positioner;
  47834. friend class Positioner;
  47835. bool containsDynamicPoints;
  47836. void applyTo (DrawablePath& path) const;
  47837. RelativePointPath& operator= (const RelativePointPath&);
  47838. JUCE_LEAK_DETECTOR (RelativePointPath);
  47839. };
  47840. #endif // __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  47841. /*** End of inlined file: juce_RelativePointPath.h ***/
  47842. #endif
  47843. #ifndef __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  47844. /*** Start of inlined file: juce_RelativeRectangle.h ***/
  47845. #ifndef __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  47846. #define __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  47847. class Component;
  47848. /**
  47849. An rectangle stored as a set of RelativeCoordinate values.
  47850. The rectangle's top, left, bottom and right edge positions are each stored as a RelativeCoordinate.
  47851. @see RelativeCoordinate, RelativePoint
  47852. */
  47853. class JUCE_API RelativeRectangle
  47854. {
  47855. public:
  47856. /** Creates a zero-size rectangle at the origin. */
  47857. RelativeRectangle();
  47858. /** Creates an absolute rectangle, relative to the origin. */
  47859. explicit RelativeRectangle (const Rectangle<float>& rect);
  47860. /** Creates a rectangle from four coordinates. */
  47861. RelativeRectangle (const RelativeCoordinate& left, const RelativeCoordinate& right,
  47862. const RelativeCoordinate& top, const RelativeCoordinate& bottom);
  47863. /** Creates a rectangle from a stringified representation.
  47864. The string must contain a sequence of 4 coordinates, separated by commas, in the order
  47865. left, top, right, bottom. The syntax for the coordinate strings is explained in the
  47866. RelativeCoordinate class.
  47867. @see toString
  47868. */
  47869. explicit RelativeRectangle (const String& stringVersion);
  47870. bool operator== (const RelativeRectangle& other) const noexcept;
  47871. bool operator!= (const RelativeRectangle& other) const noexcept;
  47872. /** Calculates the absolute position of this rectangle.
  47873. You'll need to provide a suitable Expression::Scope for looking up any coordinates that may
  47874. be needed to calculate the result.
  47875. */
  47876. const Rectangle<float> resolve (const Expression::Scope* scope) const;
  47877. /** Changes the values of this rectangle's coordinates to make it resolve to the specified position.
  47878. Calling this will leave any anchor points unchanged, but will set any absolute
  47879. or relative positions to whatever values are necessary to make the resultant position
  47880. match the position that is provided.
  47881. */
  47882. void moveToAbsolute (const Rectangle<float>& newPos, const Expression::Scope* scope);
  47883. /** Returns true if this rectangle depends on any external symbols for its position.
  47884. Coordinates that refer to symbols based on "this" are assumed not to be dynamic.
  47885. */
  47886. bool isDynamic() const;
  47887. /** Returns a string which represents this point.
  47888. This returns a comma-separated list of coordinates, in the order left, top, right, bottom. For details of
  47889. the string syntax used by the coordinates, see the RelativeCoordinate constructor notes.
  47890. The string that is returned can be passed to the RelativeRectangle constructor to recreate the rectangle.
  47891. */
  47892. String toString() const;
  47893. /** Renames a symbol if it is used by any of the coordinates.
  47894. This calls Expression::withRenamedSymbol() on the rectangle's coordinates.
  47895. */
  47896. void renameSymbol (const Expression::Symbol& oldSymbol, const String& newName, const Expression::Scope& scope);
  47897. /** Creates and sets an appropriate Component::Positioner object for the given component, which will
  47898. keep it positioned with this rectangle.
  47899. */
  47900. void applyToComponent (Component& component) const;
  47901. // The actual rectangle coords...
  47902. RelativeCoordinate left, right, top, bottom;
  47903. };
  47904. #endif // __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  47905. /*** End of inlined file: juce_RelativeRectangle.h ***/
  47906. #endif
  47907. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  47908. /*** Start of inlined file: juce_BooleanPropertyComponent.h ***/
  47909. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  47910. #define __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  47911. /**
  47912. A PropertyComponent that contains an on/off toggle button.
  47913. This type of property component can be used if you have a boolean value to
  47914. toggle on/off.
  47915. @see PropertyComponent
  47916. */
  47917. class JUCE_API BooleanPropertyComponent : public PropertyComponent,
  47918. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  47919. {
  47920. protected:
  47921. /** Creates a button component.
  47922. If you use this constructor, you must override the getState() and setState()
  47923. methods.
  47924. @param propertyName the property name to be passed to the PropertyComponent
  47925. @param buttonTextWhenTrue the text shown in the button when the value is true
  47926. @param buttonTextWhenFalse the text shown in the button when the value is false
  47927. */
  47928. BooleanPropertyComponent (const String& propertyName,
  47929. const String& buttonTextWhenTrue,
  47930. const String& buttonTextWhenFalse);
  47931. public:
  47932. /** Creates a button component.
  47933. @param valueToControl a Value object that this property should refer to.
  47934. @param propertyName the property name to be passed to the PropertyComponent
  47935. @param buttonText the text shown in the ToggleButton component
  47936. */
  47937. BooleanPropertyComponent (const Value& valueToControl,
  47938. const String& propertyName,
  47939. const String& buttonText);
  47940. /** Destructor. */
  47941. ~BooleanPropertyComponent();
  47942. /** Called to change the state of the boolean value. */
  47943. virtual void setState (bool newState);
  47944. /** Must return the current value of the property. */
  47945. virtual bool getState() const;
  47946. /** @internal */
  47947. void paint (Graphics& g);
  47948. /** @internal */
  47949. void refresh();
  47950. /** @internal */
  47951. void buttonClicked (Button*);
  47952. private:
  47953. ToggleButton button;
  47954. String onText, offText;
  47955. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BooleanPropertyComponent);
  47956. };
  47957. #endif // __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  47958. /*** End of inlined file: juce_BooleanPropertyComponent.h ***/
  47959. #endif
  47960. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  47961. /*** Start of inlined file: juce_ButtonPropertyComponent.h ***/
  47962. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  47963. #define __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  47964. /**
  47965. A PropertyComponent that contains a button.
  47966. This type of property component can be used if you need a button to trigger some
  47967. kind of action.
  47968. @see PropertyComponent
  47969. */
  47970. class JUCE_API ButtonPropertyComponent : public PropertyComponent,
  47971. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  47972. {
  47973. public:
  47974. /** Creates a button component.
  47975. @param propertyName the property name to be passed to the PropertyComponent
  47976. @param triggerOnMouseDown this is passed to the Button::setTriggeredOnMouseDown() method
  47977. */
  47978. ButtonPropertyComponent (const String& propertyName,
  47979. bool triggerOnMouseDown);
  47980. /** Destructor. */
  47981. ~ButtonPropertyComponent();
  47982. /** Called when the user clicks the button.
  47983. */
  47984. virtual void buttonClicked() = 0;
  47985. /** Returns the string that should be displayed in the button.
  47986. If you need to change this string, call refresh() to update the component.
  47987. */
  47988. virtual const String getButtonText() const = 0;
  47989. /** @internal */
  47990. void refresh();
  47991. /** @internal */
  47992. void buttonClicked (Button*);
  47993. private:
  47994. TextButton button;
  47995. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonPropertyComponent);
  47996. };
  47997. #endif // __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  47998. /*** End of inlined file: juce_ButtonPropertyComponent.h ***/
  47999. #endif
  48000. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  48001. /*** Start of inlined file: juce_ChoicePropertyComponent.h ***/
  48002. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  48003. #define __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  48004. /**
  48005. A PropertyComponent that shows its value as a combo box.
  48006. This type of property component contains a list of options and has a
  48007. combo box to choose one.
  48008. Your subclass's constructor must add some strings to the choices StringArray
  48009. and these are shown in the list.
  48010. The getIndex() method will be called to find out which option is the currently
  48011. selected one. If you call refresh() it will call getIndex() to check whether
  48012. the value has changed, and will update the combo box if needed.
  48013. If the user selects a different item from the list, setIndex() will be
  48014. called to let your class process this.
  48015. @see PropertyComponent, PropertyPanel
  48016. */
  48017. class JUCE_API ChoicePropertyComponent : public PropertyComponent,
  48018. private ComboBoxListener // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  48019. {
  48020. protected:
  48021. /** Creates the component.
  48022. Your subclass's constructor must add a list of options to the choices
  48023. member variable.
  48024. */
  48025. ChoicePropertyComponent (const String& propertyName);
  48026. public:
  48027. /** Creates the component.
  48028. @param valueToControl the value that the combo box will read and control
  48029. @param propertyName the name of the property
  48030. @param choices the list of possible values that the drop-down list will contain
  48031. @param correspondingValues a list of values corresponding to each item in the 'choices' StringArray.
  48032. These are the values that will be read and written to the
  48033. valueToControl value. This array must contain the same number of items
  48034. as the choices array
  48035. */
  48036. ChoicePropertyComponent (const Value& valueToControl,
  48037. const String& propertyName,
  48038. const StringArray& choices,
  48039. const Array <var>& correspondingValues);
  48040. /** Destructor. */
  48041. ~ChoicePropertyComponent();
  48042. /** Called when the user selects an item from the combo box.
  48043. Your subclass must use this callback to update the value that this component
  48044. represents. The index is the index of the chosen item in the choices
  48045. StringArray.
  48046. */
  48047. virtual void setIndex (int newIndex);
  48048. /** Returns the index of the item that should currently be shown.
  48049. This is the index of the item in the choices StringArray that will be
  48050. shown.
  48051. */
  48052. virtual int getIndex() const;
  48053. /** Returns the list of options. */
  48054. const StringArray& getChoices() const;
  48055. /** @internal */
  48056. void refresh();
  48057. /** @internal */
  48058. void comboBoxChanged (ComboBox*);
  48059. protected:
  48060. /** The list of options that will be shown in the combo box.
  48061. Your subclass must populate this array in its constructor. If any empty
  48062. strings are added, these will be replaced with horizontal separators (see
  48063. ComboBox::addSeparator() for more info).
  48064. */
  48065. StringArray choices;
  48066. private:
  48067. ComboBox comboBox;
  48068. bool isCustomClass;
  48069. class RemapperValueSource;
  48070. void createComboBox();
  48071. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChoicePropertyComponent);
  48072. };
  48073. #endif // __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  48074. /*** End of inlined file: juce_ChoicePropertyComponent.h ***/
  48075. #endif
  48076. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  48077. #endif
  48078. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  48079. #endif
  48080. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  48081. /*** Start of inlined file: juce_SliderPropertyComponent.h ***/
  48082. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  48083. #define __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  48084. /**
  48085. A PropertyComponent that shows its value as a slider.
  48086. @see PropertyComponent, Slider
  48087. */
  48088. class JUCE_API SliderPropertyComponent : public PropertyComponent,
  48089. private SliderListener // (can't use Slider::Listener due to idiotic VC2005 bug)
  48090. {
  48091. protected:
  48092. /** Creates the property component.
  48093. The ranges, interval and skew factor are passed to the Slider component.
  48094. If you need to customise the slider in other ways, your constructor can
  48095. access the slider member variable and change it directly.
  48096. */
  48097. SliderPropertyComponent (const String& propertyName,
  48098. double rangeMin,
  48099. double rangeMax,
  48100. double interval,
  48101. double skewFactor = 1.0);
  48102. public:
  48103. /** Creates the property component.
  48104. The ranges, interval and skew factor are passed to the Slider component.
  48105. If you need to customise the slider in other ways, your constructor can
  48106. access the slider member variable and change it directly.
  48107. */
  48108. SliderPropertyComponent (const Value& valueToControl,
  48109. const String& propertyName,
  48110. double rangeMin,
  48111. double rangeMax,
  48112. double interval,
  48113. double skewFactor = 1.0);
  48114. /** Destructor. */
  48115. ~SliderPropertyComponent();
  48116. /** Called when the user moves the slider to change its value.
  48117. Your subclass must use this method to update whatever item this property
  48118. represents.
  48119. */
  48120. virtual void setValue (double newValue);
  48121. /** Returns the value that the slider should show. */
  48122. virtual double getValue() const;
  48123. /** @internal */
  48124. void refresh();
  48125. /** @internal */
  48126. void sliderValueChanged (Slider*);
  48127. protected:
  48128. /** The slider component being used in this component.
  48129. Your subclass has access to this in case it needs to customise it in some way.
  48130. */
  48131. Slider slider;
  48132. private:
  48133. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SliderPropertyComponent);
  48134. };
  48135. #endif // __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  48136. /*** End of inlined file: juce_SliderPropertyComponent.h ***/
  48137. #endif
  48138. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  48139. /*** Start of inlined file: juce_TextPropertyComponent.h ***/
  48140. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  48141. #define __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  48142. /**
  48143. A PropertyComponent that shows its value as editable text.
  48144. @see PropertyComponent
  48145. */
  48146. class JUCE_API TextPropertyComponent : public PropertyComponent
  48147. {
  48148. protected:
  48149. /** Creates a text property component.
  48150. The maxNumChars is used to set the length of string allowable, and isMultiLine
  48151. sets whether the text editor allows carriage returns.
  48152. @see TextEditor
  48153. */
  48154. TextPropertyComponent (const String& propertyName,
  48155. int maxNumChars,
  48156. bool isMultiLine);
  48157. public:
  48158. /** Creates a text property component.
  48159. The maxNumChars is used to set the length of string allowable, and isMultiLine
  48160. sets whether the text editor allows carriage returns.
  48161. @see TextEditor
  48162. */
  48163. TextPropertyComponent (const Value& valueToControl,
  48164. const String& propertyName,
  48165. int maxNumChars,
  48166. bool isMultiLine);
  48167. /** Destructor. */
  48168. ~TextPropertyComponent();
  48169. /** Called when the user edits the text.
  48170. Your subclass must use this callback to change the value of whatever item
  48171. this property component represents.
  48172. */
  48173. virtual void setText (const String& newText);
  48174. /** Returns the text that should be shown in the text editor.
  48175. */
  48176. virtual const String getText() const;
  48177. /** @internal */
  48178. void refresh();
  48179. /** @internal */
  48180. void textWasEdited();
  48181. private:
  48182. ScopedPointer<Label> textEditor;
  48183. void createEditor (int maxNumChars, bool isMultiLine);
  48184. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextPropertyComponent);
  48185. };
  48186. #endif // __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  48187. /*** End of inlined file: juce_TextPropertyComponent.h ***/
  48188. #endif
  48189. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  48190. /*** Start of inlined file: juce_ActiveXControlComponent.h ***/
  48191. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  48192. #define __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  48193. #if JUCE_WINDOWS || DOXYGEN
  48194. /**
  48195. A Windows-specific class that can create and embed an ActiveX control inside
  48196. itself.
  48197. To use it, create one of these, put it in place and make sure it's visible in a
  48198. window, then use createControl() to instantiate an ActiveX control. The control
  48199. will then be moved and resized to follow the movements of this component.
  48200. Of course, since the control is a heavyweight window, it'll obliterate any
  48201. juce components that may overlap this component, but that's life.
  48202. */
  48203. class JUCE_API ActiveXControlComponent : public Component
  48204. {
  48205. public:
  48206. /** Create an initially-empty container. */
  48207. ActiveXControlComponent();
  48208. /** Destructor. */
  48209. ~ActiveXControlComponent();
  48210. /** Tries to create an ActiveX control and embed it in this peer.
  48211. The peer controlIID is a pointer to an IID structure - it's treated
  48212. as a void* because when including the Juce headers, you might not always
  48213. have included windows.h first, in which case IID wouldn't be defined.
  48214. e.g. @code
  48215. const IID myIID = __uuidof (QTControl);
  48216. myControlComp->createControl (&myIID);
  48217. @endcode
  48218. */
  48219. bool createControl (const void* controlIID);
  48220. /** Deletes the ActiveX control, if one has been created.
  48221. */
  48222. void deleteControl();
  48223. /** Returns true if a control is currently in use. */
  48224. bool isControlOpen() const noexcept { return control != nullptr; }
  48225. /** Does a QueryInterface call on the embedded control object.
  48226. This allows you to cast the control to whatever type of COM object you need.
  48227. The iid parameter is a pointer to an IID structure - it's treated
  48228. as a void* because when including the Juce headers, you might not always
  48229. have included windows.h first, in which case IID wouldn't be defined, but
  48230. you should just pass a pointer to an IID.
  48231. e.g. @code
  48232. const IID iid = __uuidof (IOleWindow);
  48233. IOleWindow* oleWindow = (IOleWindow*) myControlComp->queryInterface (&iid);
  48234. if (oleWindow != nullptr)
  48235. {
  48236. HWND hwnd;
  48237. oleWindow->GetWindow (&hwnd);
  48238. ...
  48239. oleWindow->Release();
  48240. }
  48241. @endcode
  48242. */
  48243. void* queryInterface (const void* iid) const;
  48244. /** Set this to false to stop mouse events being allowed through to the control.
  48245. */
  48246. void setMouseEventsAllowed (bool eventsCanReachControl);
  48247. /** Returns true if mouse events are allowed to get through to the control.
  48248. */
  48249. bool areMouseEventsAllowed() const noexcept { return mouseEventsAllowed; }
  48250. /** @internal */
  48251. void paint (Graphics& g);
  48252. /** @internal */
  48253. void* originalWndProc;
  48254. private:
  48255. class Pimpl;
  48256. friend class Pimpl;
  48257. friend class ScopedPointer <Pimpl>;
  48258. ScopedPointer <Pimpl> control;
  48259. bool mouseEventsAllowed;
  48260. void setControlBounds (const Rectangle<int>& bounds) const;
  48261. void setControlVisible (bool b) const;
  48262. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ActiveXControlComponent);
  48263. };
  48264. #endif
  48265. #endif // __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  48266. /*** End of inlined file: juce_ActiveXControlComponent.h ***/
  48267. #endif
  48268. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  48269. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  48270. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  48271. #define __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  48272. /**
  48273. A component containing controls to let the user change the audio settings of
  48274. an AudioDeviceManager object.
  48275. Very easy to use - just create one of these and show it to the user.
  48276. @see AudioDeviceManager
  48277. */
  48278. class JUCE_API AudioDeviceSelectorComponent : public Component,
  48279. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  48280. public ButtonListener,
  48281. public ChangeListener
  48282. {
  48283. public:
  48284. /** Creates the component.
  48285. If your app needs only output channels, you might ask for a maximum of 0 input
  48286. channels, and the component won't display any options for choosing the input
  48287. channels. And likewise if you're doing an input-only app.
  48288. @param deviceManager the device manager that this component should control
  48289. @param minAudioInputChannels the minimum number of audio input channels that the application needs
  48290. @param maxAudioInputChannels the maximum number of audio input channels that the application needs
  48291. @param minAudioOutputChannels the minimum number of audio output channels that the application needs
  48292. @param maxAudioOutputChannels the maximum number of audio output channels that the application needs
  48293. @param showMidiInputOptions if true, the component will allow the user to select which midi inputs are enabled
  48294. @param showMidiOutputSelector if true, the component will let the user choose a default midi output device
  48295. @param showChannelsAsStereoPairs if true, channels will be treated as pairs; if false, channels will be
  48296. treated as a set of separate mono channels.
  48297. @param hideAdvancedOptionsWithButton if true, only the minimum amount of UI components
  48298. are shown, with an "advanced" button that shows the rest of them
  48299. */
  48300. AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager,
  48301. const int minAudioInputChannels,
  48302. const int maxAudioInputChannels,
  48303. const int minAudioOutputChannels,
  48304. const int maxAudioOutputChannels,
  48305. const bool showMidiInputOptions,
  48306. const bool showMidiOutputSelector,
  48307. const bool showChannelsAsStereoPairs,
  48308. const bool hideAdvancedOptionsWithButton);
  48309. /** Destructor */
  48310. ~AudioDeviceSelectorComponent();
  48311. /** @internal */
  48312. void resized();
  48313. /** @internal */
  48314. void comboBoxChanged (ComboBox*);
  48315. /** @internal */
  48316. void buttonClicked (Button*);
  48317. /** @internal */
  48318. void changeListenerCallback (ChangeBroadcaster*);
  48319. /** @internal */
  48320. void childBoundsChanged (Component*);
  48321. private:
  48322. AudioDeviceManager& deviceManager;
  48323. ScopedPointer<ComboBox> deviceTypeDropDown;
  48324. ScopedPointer<Label> deviceTypeDropDownLabel;
  48325. ScopedPointer<Component> audioDeviceSettingsComp;
  48326. String audioDeviceSettingsCompType;
  48327. const int minOutputChannels, maxOutputChannels, minInputChannels, maxInputChannels;
  48328. const bool showChannelsAsStereoPairs;
  48329. const bool hideAdvancedOptionsWithButton;
  48330. class MidiInputSelectorComponentListBox;
  48331. friend class ScopedPointer<MidiInputSelectorComponentListBox>;
  48332. ScopedPointer<MidiInputSelectorComponentListBox> midiInputsList;
  48333. ScopedPointer<ComboBox> midiOutputSelector;
  48334. ScopedPointer<Label> midiInputsLabel, midiOutputLabel;
  48335. void updateAllControls();
  48336. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceSelectorComponent);
  48337. };
  48338. #endif // __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  48339. /*** End of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  48340. #endif
  48341. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  48342. /*** Start of inlined file: juce_BubbleComponent.h ***/
  48343. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  48344. #define __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  48345. /**
  48346. A component for showing a message or other graphics inside a speech-bubble-shaped
  48347. outline, pointing at a location on the screen.
  48348. This is a base class that just draws and positions the bubble shape, but leaves
  48349. the drawing of any content up to a subclass. See BubbleMessageComponent for a subclass
  48350. that draws a text message.
  48351. To use it, create your subclass, then either add it to a parent component or
  48352. put it on the desktop with addToDesktop (0), use setPosition() to
  48353. resize and position it, then make it visible.
  48354. @see BubbleMessageComponent
  48355. */
  48356. class JUCE_API BubbleComponent : public Component
  48357. {
  48358. protected:
  48359. /** Creates a BubbleComponent.
  48360. Your subclass will need to implement the getContentSize() and paintContent()
  48361. methods to draw the bubble's contents.
  48362. */
  48363. BubbleComponent();
  48364. public:
  48365. /** Destructor. */
  48366. ~BubbleComponent();
  48367. /** A list of permitted placements for the bubble, relative to the co-ordinates
  48368. at which it should be pointing.
  48369. @see setAllowedPlacement
  48370. */
  48371. enum BubblePlacement
  48372. {
  48373. above = 1,
  48374. below = 2,
  48375. left = 4,
  48376. right = 8
  48377. };
  48378. /** Tells the bubble which positions it's allowed to put itself in, relative to the
  48379. point at which it's pointing.
  48380. By default when setPosition() is called, the bubble will place itself either
  48381. above, below, left, or right of the target area. You can pass in a bitwise-'or' of
  48382. the values in BubblePlacement to restrict this choice.
  48383. E.g. if you only want your bubble to appear above or below the target area,
  48384. use setAllowedPlacement (above | below);
  48385. @see BubblePlacement
  48386. */
  48387. void setAllowedPlacement (int newPlacement);
  48388. /** Moves and resizes the bubble to point at a given component.
  48389. This will resize the bubble to fit its content, then find a position for it
  48390. so that it's next to, but doesn't overlap the given component.
  48391. It'll put itself either above, below, or to the side of the component depending
  48392. on where there's the most space, honouring any restrictions that were set
  48393. with setAllowedPlacement().
  48394. */
  48395. void setPosition (Component* componentToPointTo);
  48396. /** Moves and resizes the bubble to point at a given point.
  48397. This will resize the bubble to fit its content, then position it
  48398. so that the tip of the bubble points to the given co-ordinate. The co-ordinates
  48399. are relative to either the bubble component's parent component if it has one, or
  48400. they are screen co-ordinates if not.
  48401. It'll put itself either above, below, or to the side of this point, depending
  48402. on where there's the most space, honouring any restrictions that were set
  48403. with setAllowedPlacement().
  48404. */
  48405. void setPosition (int arrowTipX,
  48406. int arrowTipY);
  48407. /** Moves and resizes the bubble to point at a given rectangle.
  48408. This will resize the bubble to fit its content, then find a position for it
  48409. so that it's next to, but doesn't overlap the given rectangle. The rectangle's
  48410. co-ordinates are relative to either the bubble component's parent component
  48411. if it has one, or they are screen co-ordinates if not.
  48412. It'll put itself either above, below, or to the side of the component depending
  48413. on where there's the most space, honouring any restrictions that were set
  48414. with setAllowedPlacement().
  48415. */
  48416. void setPosition (const Rectangle<int>& rectangleToPointTo);
  48417. protected:
  48418. /** Subclasses should override this to return the size of the content they
  48419. want to draw inside the bubble.
  48420. */
  48421. virtual void getContentSize (int& width, int& height) = 0;
  48422. /** Subclasses should override this to draw their bubble's contents.
  48423. The graphics object's clip region and the dimensions passed in here are
  48424. set up to paint just the rectangle inside the bubble.
  48425. */
  48426. virtual void paintContent (Graphics& g, int width, int height) = 0;
  48427. public:
  48428. /** @internal */
  48429. void paint (Graphics& g);
  48430. private:
  48431. Rectangle<int> content;
  48432. int side, allowablePlacements;
  48433. float arrowTipX, arrowTipY;
  48434. DropShadowEffect shadow;
  48435. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BubbleComponent);
  48436. };
  48437. #endif // __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  48438. /*** End of inlined file: juce_BubbleComponent.h ***/
  48439. #endif
  48440. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  48441. /*** Start of inlined file: juce_BubbleMessageComponent.h ***/
  48442. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  48443. #define __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  48444. /**
  48445. A speech-bubble component that displays a short message.
  48446. This can be used to show a message with the tail of the speech bubble
  48447. pointing to a particular component or location on the screen.
  48448. @see BubbleComponent
  48449. */
  48450. class JUCE_API BubbleMessageComponent : public BubbleComponent,
  48451. private Timer
  48452. {
  48453. public:
  48454. /** Creates a bubble component.
  48455. After creating one a BubbleComponent, do the following:
  48456. - add it to an appropriate parent component, or put it on the
  48457. desktop with Component::addToDesktop (0).
  48458. - use the showAt() method to show a message.
  48459. - it will make itself invisible after it times-out (and can optionally
  48460. also delete itself), or you can reuse it somewhere else by calling
  48461. showAt() again.
  48462. */
  48463. BubbleMessageComponent (int fadeOutLengthMs = 150);
  48464. /** Destructor. */
  48465. ~BubbleMessageComponent();
  48466. /** Shows a message bubble at a particular position.
  48467. This shows the bubble with its stem pointing to the given location
  48468. (co-ordinates being relative to its parent component).
  48469. For details about exactly how it decides where to position itself, see
  48470. BubbleComponent::updatePosition().
  48471. @param x the x co-ordinate of end of the bubble's tail
  48472. @param y the y co-ordinate of end of the bubble's tail
  48473. @param message the text to display
  48474. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  48475. from its parent compnent. If this is 0 or less, it
  48476. will stay there until manually removed.
  48477. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  48478. mouse button is pressed (anywhere on the screen)
  48479. @param deleteSelfAfterUse if true, then the component will delete itself after
  48480. it becomes invisible
  48481. */
  48482. void showAt (int x, int y,
  48483. const String& message,
  48484. int numMillisecondsBeforeRemoving,
  48485. bool removeWhenMouseClicked = true,
  48486. bool deleteSelfAfterUse = false);
  48487. /** Shows a message bubble next to a particular component.
  48488. This shows the bubble with its stem pointing at the given component.
  48489. For details about exactly how it decides where to position itself, see
  48490. BubbleComponent::updatePosition().
  48491. @param component the component that you want to point at
  48492. @param message the text to display
  48493. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  48494. from its parent compnent. If this is 0 or less, it
  48495. will stay there until manually removed.
  48496. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  48497. mouse button is pressed (anywhere on the screen)
  48498. @param deleteSelfAfterUse if true, then the component will delete itself after
  48499. it becomes invisible
  48500. */
  48501. void showAt (Component* component,
  48502. const String& message,
  48503. int numMillisecondsBeforeRemoving,
  48504. bool removeWhenMouseClicked = true,
  48505. bool deleteSelfAfterUse = false);
  48506. /** @internal */
  48507. void getContentSize (int& w, int& h);
  48508. /** @internal */
  48509. void paintContent (Graphics& g, int w, int h);
  48510. /** @internal */
  48511. void timerCallback();
  48512. private:
  48513. int fadeOutLength, mouseClickCounter;
  48514. TextLayout textLayout;
  48515. int64 expiryTime;
  48516. bool deleteAfterUse;
  48517. void init (int numMillisecondsBeforeRemoving,
  48518. bool removeWhenMouseClicked,
  48519. bool deleteSelfAfterUse);
  48520. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BubbleMessageComponent);
  48521. };
  48522. #endif // __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  48523. /*** End of inlined file: juce_BubbleMessageComponent.h ***/
  48524. #endif
  48525. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  48526. /*** Start of inlined file: juce_ColourSelector.h ***/
  48527. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  48528. #define __JUCE_COLOURSELECTOR_JUCEHEADER__
  48529. /**
  48530. A component that lets the user choose a colour.
  48531. This shows RGB sliders and a colourspace that the user can pick colours from.
  48532. This class is also a ChangeBroadcaster, so listeners can register to be told
  48533. when the colour changes.
  48534. */
  48535. class JUCE_API ColourSelector : public Component,
  48536. public ChangeBroadcaster,
  48537. protected SliderListener
  48538. {
  48539. public:
  48540. /** Options for the type of selector to show. These are passed into the constructor. */
  48541. enum ColourSelectorOptions
  48542. {
  48543. showAlphaChannel = 1 << 0, /**< if set, the colour's alpha channel can be changed as well as its RGB. */
  48544. showColourAtTop = 1 << 1, /**< if set, a swatch of the colour is shown at the top of the component. */
  48545. showSliders = 1 << 2, /**< if set, RGB sliders are shown at the bottom of the component. */
  48546. showColourspace = 1 << 3 /**< if set, a big HSV selector is shown. */
  48547. };
  48548. /** Creates a ColourSelector object.
  48549. The flags are a combination of values from the ColourSelectorOptions enum, specifying
  48550. which of the selector's features should be visible.
  48551. The edgeGap value specifies the amount of space to leave around the edge.
  48552. gapAroundColourSpaceComponent indicates how much of a gap to put around the
  48553. colourspace and hue selector components.
  48554. */
  48555. ColourSelector (int sectionsToShow = (showAlphaChannel | showColourAtTop | showSliders | showColourspace),
  48556. int edgeGap = 4,
  48557. int gapAroundColourSpaceComponent = 7);
  48558. /** Destructor. */
  48559. ~ColourSelector();
  48560. /** Returns the colour that the user has currently selected.
  48561. The ColourSelector class is also a ChangeBroadcaster, so listeners can
  48562. register to be told when the colour changes.
  48563. @see setCurrentColour
  48564. */
  48565. const Colour getCurrentColour() const;
  48566. /** Changes the colour that is currently being shown.
  48567. */
  48568. void setCurrentColour (const Colour& newColour);
  48569. /** Tells the selector how many preset colour swatches you want to have on the component.
  48570. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  48571. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  48572. their values.
  48573. */
  48574. virtual int getNumSwatches() const;
  48575. /** Called by the selector to find out the colour of one of the swatches.
  48576. Your subclass should return the colour of the swatch with the given index.
  48577. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  48578. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  48579. their values.
  48580. */
  48581. virtual const Colour getSwatchColour (int index) const;
  48582. /** Called by the selector when the user puts a new colour into one of the swatches.
  48583. Your subclass should change the colour of the swatch with the given index.
  48584. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  48585. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  48586. their values.
  48587. */
  48588. virtual void setSwatchColour (int index, const Colour& newColour) const;
  48589. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  48590. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  48591. methods.
  48592. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  48593. */
  48594. enum ColourIds
  48595. {
  48596. backgroundColourId = 0x1007000, /**< the colour used to fill the component's background. */
  48597. labelTextColourId = 0x1007001 /**< the colour used for the labels next to the sliders. */
  48598. };
  48599. private:
  48600. class ColourSpaceView;
  48601. class HueSelectorComp;
  48602. class SwatchComponent;
  48603. friend class ColourSpaceView;
  48604. friend class ScopedPointer<ColourSpaceView>;
  48605. friend class HueSelectorComp;
  48606. friend class ScopedPointer<HueSelectorComp>;
  48607. Colour colour;
  48608. float h, s, v;
  48609. ScopedPointer<Slider> sliders[4];
  48610. ScopedPointer<ColourSpaceView> colourSpace;
  48611. ScopedPointer<HueSelectorComp> hueSelector;
  48612. OwnedArray <SwatchComponent> swatchComponents;
  48613. const int flags;
  48614. int edgeGap;
  48615. Rectangle<int> previewArea;
  48616. void setHue (float newH);
  48617. void setSV (float newS, float newV);
  48618. void updateHSV();
  48619. void update();
  48620. void sliderValueChanged (Slider*);
  48621. void paint (Graphics& g);
  48622. void resized();
  48623. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ColourSelector);
  48624. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  48625. // This constructor is here temporarily to prevent old code compiling, because the parameters
  48626. // have changed - if you get an error here, update your code to use the new constructor instead..
  48627. ColourSelector (bool);
  48628. #endif
  48629. };
  48630. #endif // __JUCE_COLOURSELECTOR_JUCEHEADER__
  48631. /*** End of inlined file: juce_ColourSelector.h ***/
  48632. #endif
  48633. #ifndef __JUCE_DIRECTSHOWCOMPONENT_JUCEHEADER__
  48634. /*** Start of inlined file: juce_DirectShowComponent.h ***/
  48635. #ifndef __JUCE_DIRECTSHOWCOMPONENT_JUCEHEADER__
  48636. #define __JUCE_DIRECTSHOWCOMPONENT_JUCEHEADER__
  48637. #if JUCE_DIRECTSHOW || DOXYGEN
  48638. /**
  48639. A window that can play back a DirectShow video.
  48640. @note Controller is not implemented
  48641. */
  48642. class JUCE_API DirectShowComponent : public Component
  48643. {
  48644. public:
  48645. /** DirectShow video renderer type.
  48646. See MSDN for adivce about choosing the right renderer.
  48647. */
  48648. enum VideoRendererType
  48649. {
  48650. dshowDefault, /**< VMR7 for Windows XP, EVR for Windows Vista and later */
  48651. dshowVMR7, /**< Video Mixing Renderer 7 */
  48652. dshowEVR /**< Enhanced Video Renderer */
  48653. };
  48654. /** Creates a DirectShowComponent, initially blank.
  48655. Use the loadMovie() method to load a video once you've added the
  48656. component to a window, (or put it on the desktop as a heavyweight window).
  48657. Loading a video when the component isn't visible can cause problems, as
  48658. DirectShow needs a window handle to initialise properly.
  48659. @see VideoRendererType
  48660. */
  48661. DirectShowComponent (VideoRendererType type = dshowDefault);
  48662. /** Destructor. */
  48663. ~DirectShowComponent();
  48664. /** Returns true if DirectShow is installed and working on this machine. */
  48665. static bool isDirectShowAvailable();
  48666. /** Tries to load a DirectShow video from a file or URL into the player.
  48667. It's best to call this function once you've added the component to a window,
  48668. (or put it on the desktop as a heavyweight window). Loading a video when the
  48669. component isn't visible can cause problems, because DirectShow needs a window
  48670. handle to do its stuff.
  48671. @param fileOrURLPath the file or URL path to open
  48672. @returns true if the video opens successfully
  48673. */
  48674. bool loadMovie (const String& fileOrURLPath);
  48675. /** Tries to load a DirectShow video from a file into the player.
  48676. It's best to call this function once you've added the component to a window,
  48677. (or put it on the desktop as a heavyweight window). Loading a video when the
  48678. component isn't visible can cause problems, because DirectShow needs a window
  48679. handle to do its stuff.
  48680. @param videoFile the video file to open
  48681. @returns true if the video opens successfully
  48682. */
  48683. bool loadMovie (const File& videoFile);
  48684. /** Tries to load a DirectShow video from a URL into the player.
  48685. It's best to call this function once you've added the component to a window,
  48686. (or put it on the desktop as a heavyweight window). Loading a video when the
  48687. component isn't visible can cause problems, because DirectShow needs a window
  48688. handle to do its stuff.
  48689. @param videoURL the video URL to open
  48690. @returns true if the video opens successfully
  48691. */
  48692. bool loadMovie (const URL& videoURL);
  48693. /** Closes the video, if one is open. */
  48694. void closeMovie();
  48695. /** Returns the file path or URL from which the video file was loaded.
  48696. If there isn't one, this returns an empty string.
  48697. */
  48698. File getCurrentMoviePath() const;
  48699. /** Returns true if there's currently a video open. */
  48700. bool isMovieOpen() const;
  48701. /** Returns the length of the video, in seconds. */
  48702. double getMovieDuration() const;
  48703. /** Returns the video's natural size, in pixels.
  48704. You can use this to resize the component to show the video at its preferred
  48705. scale.
  48706. If no video is loaded, the size returned will be 0 x 0.
  48707. */
  48708. void getMovieNormalSize (int& width, int& height) const;
  48709. /** This will position the component within a given area, keeping its aspect
  48710. ratio correct according to the video's normal size.
  48711. The component will be made as large as it can go within the space, and will
  48712. be aligned according to the justification value if this means there are gaps at
  48713. the top or sides.
  48714. @note Not implemented
  48715. */
  48716. void setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  48717. const RectanglePlacement& placement);
  48718. /** Starts the video playing. */
  48719. void play();
  48720. /** Stops the video playing. */
  48721. void stop();
  48722. /** Returns true if the video is currently playing. */
  48723. bool isPlaying() const;
  48724. /** Moves the video's position back to the start. */
  48725. void goToStart();
  48726. /** Sets the video's position to a given time. */
  48727. void setPosition (double seconds);
  48728. /** Returns the current play position of the video. */
  48729. double getPosition() const;
  48730. /** Changes the video playback rate.
  48731. A value of 1 is normal speed, greater values play it proportionately faster,
  48732. smaller values play it slower.
  48733. */
  48734. void setSpeed (float newSpeed);
  48735. /** Changes the video's playback volume.
  48736. @param newVolume the volume in the range 0 (silent) to 1.0 (full)
  48737. */
  48738. void setMovieVolume (float newVolume);
  48739. /** Returns the video's playback volume.
  48740. @returns the volume in the range 0 (silent) to 1.0 (full)
  48741. */
  48742. float getMovieVolume() const;
  48743. /** Tells the video whether it should loop. */
  48744. void setLooping (bool shouldLoop);
  48745. /** Returns true if the video is currently looping.
  48746. @see setLooping
  48747. */
  48748. bool isLooping() const;
  48749. /** @internal */
  48750. void paint (Graphics& g);
  48751. private:
  48752. String videoPath;
  48753. bool videoLoaded, looping;
  48754. class DirectShowContext;
  48755. friend class DirectShowContext;
  48756. friend class ScopedPointer <DirectShowContext>;
  48757. ScopedPointer <DirectShowContext> context;
  48758. class DirectShowComponentWatcher;
  48759. friend class DirectShowComponentWatcher;
  48760. friend class ScopedPointer <DirectShowComponentWatcher>;
  48761. ScopedPointer <DirectShowComponentWatcher> componentWatcher;
  48762. bool needToUpdateViewport, needToRecreateNativeWindow;
  48763. void updateContextPosition();
  48764. void showContext (bool shouldBeVisible);
  48765. void recreateNativeWindowAsync();
  48766. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectShowComponent);
  48767. };
  48768. #endif
  48769. #endif // __JUCE_DIRECTSHOWCOMPONENT_JUCEHEADER__
  48770. /*** End of inlined file: juce_DirectShowComponent.h ***/
  48771. #endif
  48772. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  48773. #endif
  48774. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  48775. /*** Start of inlined file: juce_MidiKeyboardComponent.h ***/
  48776. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  48777. #define __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  48778. /**
  48779. A component that displays a piano keyboard, whose notes can be clicked on.
  48780. This component will mimic a physical midi keyboard, showing the current state of
  48781. a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
  48782. notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
  48783. Another feature is that the computer keyboard can also be used to play notes. By
  48784. default it maps the top two rows of a standard querty keyboard to the notes, but
  48785. these can be remapped if needed. It will only respond to keypresses when it has
  48786. the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
  48787. The component is also a ChangeBroadcaster, so if you want to be informed when the
  48788. keyboard is scrolled, you can register a ChangeListener for callbacks.
  48789. @see MidiKeyboardState
  48790. */
  48791. class JUCE_API MidiKeyboardComponent : public Component,
  48792. public MidiKeyboardStateListener,
  48793. public ChangeBroadcaster,
  48794. private Timer,
  48795. private AsyncUpdater
  48796. {
  48797. public:
  48798. /** The direction of the keyboard.
  48799. @see setOrientation
  48800. */
  48801. enum Orientation
  48802. {
  48803. horizontalKeyboard,
  48804. verticalKeyboardFacingLeft,
  48805. verticalKeyboardFacingRight,
  48806. };
  48807. /** Creates a MidiKeyboardComponent.
  48808. @param state the midi keyboard model that this component will represent
  48809. @param orientation whether the keyboard is horizonal or vertical
  48810. */
  48811. MidiKeyboardComponent (MidiKeyboardState& state,
  48812. Orientation orientation);
  48813. /** Destructor. */
  48814. ~MidiKeyboardComponent();
  48815. /** Changes the velocity used in midi note-on messages that are triggered by clicking
  48816. on the component.
  48817. Values are 0 to 1.0, where 1.0 is the heaviest.
  48818. @see setMidiChannel
  48819. */
  48820. void setVelocity (float velocity, bool useMousePositionForVelocity);
  48821. /** Changes the midi channel number that will be used for events triggered by clicking
  48822. on the component.
  48823. The channel must be between 1 and 16 (inclusive). This is the channel that will be
  48824. passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
  48825. Although this is the channel used for outgoing events, the component can display
  48826. incoming events from more than one channel - see setMidiChannelsToDisplay()
  48827. @see setVelocity
  48828. */
  48829. void setMidiChannel (int midiChannelNumber);
  48830. /** Returns the midi channel that the keyboard is using for midi messages.
  48831. @see setMidiChannel
  48832. */
  48833. int getMidiChannel() const noexcept { return midiChannel; }
  48834. /** Sets a mask to indicate which incoming midi channels should be represented by
  48835. key movements.
  48836. The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
  48837. If the MidiKeyboardState has a key down for any of the channels whose bits are set
  48838. in this mask, the on-screen keys will also go down.
  48839. By default, this mask is set to 0xffff (all channels displayed).
  48840. @see setMidiChannel
  48841. */
  48842. void setMidiChannelsToDisplay (int midiChannelMask);
  48843. /** Returns the current set of midi channels represented by the component.
  48844. This is the value that was set with setMidiChannelsToDisplay().
  48845. */
  48846. int getMidiChannelsToDisplay() const noexcept { return midiInChannelMask; }
  48847. /** Changes the width used to draw the white keys. */
  48848. void setKeyWidth (float widthInPixels);
  48849. /** Returns the width that was set by setKeyWidth(). */
  48850. float getKeyWidth() const noexcept { return keyWidth; }
  48851. /** Changes the keyboard's current direction. */
  48852. void setOrientation (Orientation newOrientation);
  48853. /** Returns the keyboard's current direction. */
  48854. const Orientation getOrientation() const noexcept { return orientation; }
  48855. /** Sets the range of midi notes that the keyboard will be limited to.
  48856. By default the range is 0 to 127 (inclusive), but you can limit this if you
  48857. only want a restricted set of the keys to be shown.
  48858. Note that the values here are inclusive and must be between 0 and 127.
  48859. */
  48860. void setAvailableRange (int lowestNote,
  48861. int highestNote);
  48862. /** Returns the first note in the available range.
  48863. @see setAvailableRange
  48864. */
  48865. int getRangeStart() const noexcept { return rangeStart; }
  48866. /** Returns the last note in the available range.
  48867. @see setAvailableRange
  48868. */
  48869. int getRangeEnd() const noexcept { return rangeEnd; }
  48870. /** If the keyboard extends beyond the size of the component, this will scroll
  48871. it to show the given key at the start.
  48872. Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
  48873. base class to send a callback to any ChangeListeners that have been registered.
  48874. */
  48875. void setLowestVisibleKey (int noteNumber);
  48876. /** Returns the number of the first key shown in the component.
  48877. @see setLowestVisibleKey
  48878. */
  48879. int getLowestVisibleKey() const noexcept { return firstKey; }
  48880. /** Returns the length of the black notes.
  48881. This will be their vertical or horizontal length, depending on the keyboard's orientation.
  48882. */
  48883. int getBlackNoteLength() const noexcept { return blackNoteLength; }
  48884. /** If set to true, then scroll buttons will appear at either end of the keyboard
  48885. if there are too many notes to fit them all in the component at once.
  48886. */
  48887. void setScrollButtonsVisible (bool canScroll);
  48888. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  48889. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  48890. methods.
  48891. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  48892. */
  48893. enum ColourIds
  48894. {
  48895. whiteNoteColourId = 0x1005000,
  48896. blackNoteColourId = 0x1005001,
  48897. keySeparatorLineColourId = 0x1005002,
  48898. mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
  48899. keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
  48900. textLabelColourId = 0x1005005,
  48901. upDownButtonBackgroundColourId = 0x1005006,
  48902. upDownButtonArrowColourId = 0x1005007
  48903. };
  48904. /** Returns the position within the component of the left-hand edge of a key.
  48905. Depending on the keyboard's orientation, this may be a horizontal or vertical
  48906. distance, in either direction.
  48907. */
  48908. int getKeyStartPosition (const int midiNoteNumber) const;
  48909. /** Deletes all key-mappings.
  48910. @see setKeyPressForNote
  48911. */
  48912. void clearKeyMappings();
  48913. /** Maps a key-press to a given note.
  48914. @param key the key that should trigger the note
  48915. @param midiNoteOffsetFromC how many semitones above C the triggered note should
  48916. be. The actual midi note that gets played will be
  48917. this value + (12 * the current base octave). To change
  48918. the base octave, see setKeyPressBaseOctave()
  48919. */
  48920. void setKeyPressForNote (const KeyPress& key,
  48921. int midiNoteOffsetFromC);
  48922. /** Removes any key-mappings for a given note.
  48923. For a description of what the note number means, see setKeyPressForNote().
  48924. */
  48925. void removeKeyPressForNote (int midiNoteOffsetFromC);
  48926. /** Changes the base note above which key-press-triggered notes are played.
  48927. The set of key-mappings that trigger notes can be moved up and down to cover
  48928. the entire scale using this method.
  48929. The value passed in is an octave number between 0 and 10 (inclusive), and
  48930. indicates which C is the base note to which the key-mapped notes are
  48931. relative.
  48932. */
  48933. void setKeyPressBaseOctave (int newOctaveNumber);
  48934. /** This sets the octave number which is shown as the octave number for middle C.
  48935. This affects only the default implementation of getWhiteNoteText(), which
  48936. passes this octave number to MidiMessage::getMidiNoteName() in order to
  48937. get the note text. See MidiMessage::getMidiNoteName() for more info about
  48938. the parameter.
  48939. By default this value is set to 3.
  48940. @see getOctaveForMiddleC
  48941. */
  48942. void setOctaveForMiddleC (int octaveNumForMiddleC);
  48943. /** This returns the value set by setOctaveForMiddleC().
  48944. @see setOctaveForMiddleC
  48945. */
  48946. int getOctaveForMiddleC() const noexcept { return octaveNumForMiddleC; }
  48947. /** @internal */
  48948. void paint (Graphics& g);
  48949. /** @internal */
  48950. void resized();
  48951. /** @internal */
  48952. void mouseMove (const MouseEvent& e);
  48953. /** @internal */
  48954. void mouseDrag (const MouseEvent& e);
  48955. /** @internal */
  48956. void mouseDown (const MouseEvent& e);
  48957. /** @internal */
  48958. void mouseUp (const MouseEvent& e);
  48959. /** @internal */
  48960. void mouseEnter (const MouseEvent& e);
  48961. /** @internal */
  48962. void mouseExit (const MouseEvent& e);
  48963. /** @internal */
  48964. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  48965. /** @internal */
  48966. void timerCallback();
  48967. /** @internal */
  48968. bool keyStateChanged (bool isKeyDown);
  48969. /** @internal */
  48970. void focusLost (FocusChangeType cause);
  48971. /** @internal */
  48972. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  48973. /** @internal */
  48974. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  48975. /** @internal */
  48976. void handleAsyncUpdate();
  48977. /** @internal */
  48978. void colourChanged();
  48979. protected:
  48980. /** Draws a white note in the given rectangle.
  48981. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  48982. currently pressed down.
  48983. When doing this, be sure to note the keyboard's orientation.
  48984. */
  48985. virtual void drawWhiteNote (int midiNoteNumber,
  48986. Graphics& g,
  48987. int x, int y, int w, int h,
  48988. bool isDown, bool isOver,
  48989. const Colour& lineColour,
  48990. const Colour& textColour);
  48991. /** Draws a black note in the given rectangle.
  48992. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  48993. currently pressed down.
  48994. When doing this, be sure to note the keyboard's orientation.
  48995. */
  48996. virtual void drawBlackNote (int midiNoteNumber,
  48997. Graphics& g,
  48998. int x, int y, int w, int h,
  48999. bool isDown, bool isOver,
  49000. const Colour& noteFillColour);
  49001. /** Allows text to be drawn on the white notes.
  49002. By default this is used to label the C in each octave, but could be used for other things.
  49003. @see setOctaveForMiddleC
  49004. */
  49005. virtual const String getWhiteNoteText (const int midiNoteNumber);
  49006. /** Draws the up and down buttons that change the base note. */
  49007. virtual void drawUpDownButton (Graphics& g, int w, int h,
  49008. const bool isMouseOver,
  49009. const bool isButtonPressed,
  49010. const bool movesOctavesUp);
  49011. /** Callback when the mouse is clicked on a key.
  49012. You could use this to do things like handle right-clicks on keys, etc.
  49013. Return true if you want the click to trigger the note, or false if you
  49014. want to handle it yourself and not have the note played.
  49015. @see mouseDraggedToKey
  49016. */
  49017. virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e);
  49018. /** Callback when the mouse is dragged from one key onto another.
  49019. @see mouseDownOnKey
  49020. */
  49021. virtual void mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e);
  49022. /** Calculates the positon of a given midi-note.
  49023. This can be overridden to create layouts with custom key-widths.
  49024. @param midiNoteNumber the note to find
  49025. @param keyWidth the desired width in pixels of one key - see setKeyWidth()
  49026. @param x the x position of the left-hand edge of the key (this method
  49027. always works in terms of a horizontal keyboard)
  49028. @param w the width of the key
  49029. */
  49030. virtual void getKeyPosition (int midiNoteNumber, float keyWidth,
  49031. int& x, int& w) const;
  49032. private:
  49033. friend class MidiKeyboardUpDownButton;
  49034. MidiKeyboardState& state;
  49035. int xOffset, blackNoteLength;
  49036. float keyWidth;
  49037. Orientation orientation;
  49038. int midiChannel, midiInChannelMask;
  49039. float velocity;
  49040. int noteUnderMouse, mouseDownNote;
  49041. BigInteger keysPressed, keysCurrentlyDrawnDown;
  49042. int rangeStart, rangeEnd, firstKey;
  49043. bool canScroll, mouseDragging, useMousePositionForVelocity;
  49044. ScopedPointer<Button> scrollDown, scrollUp;
  49045. Array <KeyPress> keyPresses;
  49046. Array <int> keyPressNotes;
  49047. int keyMappingOctave;
  49048. int octaveNumForMiddleC;
  49049. static const uint8 whiteNotes[];
  49050. static const uint8 blackNotes[];
  49051. void getKeyPos (int midiNoteNumber, int& x, int& w) const;
  49052. int xyToNote (const Point<int>& pos, float& mousePositionVelocity);
  49053. int remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const;
  49054. void resetAnyKeysInUse();
  49055. void updateNoteUnderMouse (const Point<int>& pos);
  49056. void repaintNote (const int midiNoteNumber);
  49057. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiKeyboardComponent);
  49058. };
  49059. #endif // __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  49060. /*** End of inlined file: juce_MidiKeyboardComponent.h ***/
  49061. #endif
  49062. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  49063. /*** Start of inlined file: juce_NSViewComponent.h ***/
  49064. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  49065. #define __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  49066. #if ! DOXYGEN
  49067. class NSViewComponentInternal;
  49068. #endif
  49069. #if JUCE_MAC || DOXYGEN
  49070. /**
  49071. A Mac-specific class that can create and embed an NSView inside itself.
  49072. To use it, create one of these, put it in place and make sure it's visible in a
  49073. window, then use setView() to assign an NSView to it. The view will then be
  49074. moved and resized to follow the movements of this component.
  49075. Of course, since the view is a native object, it'll obliterate any
  49076. juce components that may overlap this component, but that's life.
  49077. */
  49078. class JUCE_API NSViewComponent : public Component
  49079. {
  49080. public:
  49081. /** Create an initially-empty container. */
  49082. NSViewComponent();
  49083. /** Destructor. */
  49084. ~NSViewComponent();
  49085. /** Assigns an NSView to this peer.
  49086. The view will be retained and released by this component for as long as
  49087. it is needed. To remove the current view, just call setView (nullptr).
  49088. Note: a void* is used here to avoid including the cocoa headers as
  49089. part of the juce.h, but the method expects an NSView*.
  49090. */
  49091. void setView (void* nsView);
  49092. /** Returns the current NSView.
  49093. Note: a void* is returned here to avoid including the cocoa headers as
  49094. a requirement of juce.h, so you should just cast the object to an NSView*.
  49095. */
  49096. void* getView() const;
  49097. /** Resizes this component to fit the view that it contains. */
  49098. void resizeToFitView();
  49099. /** @internal */
  49100. void paint (Graphics& g);
  49101. private:
  49102. friend class NSViewComponentInternal;
  49103. ScopedPointer <NSViewComponentInternal> info;
  49104. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponent);
  49105. };
  49106. #endif
  49107. #endif // __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  49108. /*** End of inlined file: juce_NSViewComponent.h ***/
  49109. #endif
  49110. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  49111. /*** Start of inlined file: juce_OpenGLComponent.h ***/
  49112. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  49113. #define __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  49114. // this is used to disable OpenGL, and is defined in juce_Config.h
  49115. #if JUCE_OPENGL || DOXYGEN
  49116. /**
  49117. Represents the various properties of an OpenGL bitmap format.
  49118. @see OpenGLComponent::setPixelFormat
  49119. */
  49120. class JUCE_API OpenGLPixelFormat
  49121. {
  49122. public:
  49123. /** Creates an OpenGLPixelFormat.
  49124. The default constructor just initialises the object as a simple 8-bit
  49125. RGBA format.
  49126. */
  49127. OpenGLPixelFormat (int bitsPerRGBComponent = 8,
  49128. int alphaBits = 8,
  49129. int depthBufferBits = 16,
  49130. int stencilBufferBits = 0);
  49131. OpenGLPixelFormat (const OpenGLPixelFormat&);
  49132. OpenGLPixelFormat& operator= (const OpenGLPixelFormat&);
  49133. bool operator== (const OpenGLPixelFormat&) const;
  49134. int redBits; /**< The number of bits per pixel to use for the red channel. */
  49135. int greenBits; /**< The number of bits per pixel to use for the green channel. */
  49136. int blueBits; /**< The number of bits per pixel to use for the blue channel. */
  49137. int alphaBits; /**< The number of bits per pixel to use for the alpha channel. */
  49138. int depthBufferBits; /**< The number of bits per pixel to use for a depth buffer. */
  49139. int stencilBufferBits; /**< The number of bits per pixel to use for a stencil buffer. */
  49140. int accumulationBufferRedBits; /**< The number of bits per pixel to use for an accumulation buffer's red channel. */
  49141. int accumulationBufferGreenBits; /**< The number of bits per pixel to use for an accumulation buffer's green channel. */
  49142. int accumulationBufferBlueBits; /**< The number of bits per pixel to use for an accumulation buffer's blue channel. */
  49143. int accumulationBufferAlphaBits; /**< The number of bits per pixel to use for an accumulation buffer's alpha channel. */
  49144. uint8 fullSceneAntiAliasingNumSamples; /**< The number of samples to use in full-scene anti-aliasing (if available). */
  49145. /** Returns a list of all the pixel formats that can be used in this system.
  49146. A reference component is needed in case there are multiple screens with different
  49147. capabilities - in which case, the one that the component is on will be used.
  49148. */
  49149. static void getAvailablePixelFormats (Component* component,
  49150. OwnedArray <OpenGLPixelFormat>& results);
  49151. private:
  49152. JUCE_LEAK_DETECTOR (OpenGLPixelFormat);
  49153. };
  49154. /**
  49155. A base class for types of OpenGL context.
  49156. An OpenGLComponent will supply its own context for drawing in its window.
  49157. */
  49158. class JUCE_API OpenGLContext
  49159. {
  49160. public:
  49161. /** Destructor. */
  49162. virtual ~OpenGLContext();
  49163. /** Makes this context the currently active one. */
  49164. virtual bool makeActive() const noexcept = 0;
  49165. /** If this context is currently active, it is disactivated. */
  49166. virtual bool makeInactive() const noexcept = 0;
  49167. /** Returns true if this context is currently active. */
  49168. virtual bool isActive() const noexcept = 0;
  49169. /** Swaps the buffers (if the context can do this). */
  49170. virtual void swapBuffers() = 0;
  49171. /** Sets whether the context checks the vertical sync before swapping.
  49172. The value is the number of frames to allow between buffer-swapping. This is
  49173. fairly system-dependent, but 0 turns off syncing, 1 makes it swap on frame-boundaries,
  49174. and greater numbers indicate that it should swap less often.
  49175. Returns true if it sets the value successfully.
  49176. */
  49177. virtual bool setSwapInterval (int numFramesPerSwap) = 0;
  49178. /** Returns the current swap-sync interval.
  49179. See setSwapInterval() for info about the value returned.
  49180. */
  49181. virtual int getSwapInterval() const = 0;
  49182. /** Returns the pixel format being used by this context. */
  49183. virtual const OpenGLPixelFormat getPixelFormat() const = 0;
  49184. /** For windowed contexts, this moves the context within the bounds of
  49185. its parent window.
  49186. */
  49187. virtual void updateWindowPosition (const Rectangle<int>& bounds) = 0;
  49188. /** For windowed contexts, this triggers a repaint of the window.
  49189. (Not relevent on all platforms).
  49190. */
  49191. virtual void repaint() = 0;
  49192. /** Returns an OS-dependent handle to the raw GL context.
  49193. On win32, this will be a HGLRC; on the Mac, an AGLContext; on Linux,
  49194. a GLXContext.
  49195. */
  49196. virtual void* getRawContext() const noexcept = 0;
  49197. /** Deletes the context.
  49198. This must only be called on the message thread, or will deadlock.
  49199. On background threads, call getCurrentContext()->deleteContext(), but be careful not
  49200. to call any other OpenGL function afterwards.
  49201. This doesn't touch other resources, such as window handles, etc.
  49202. You'll probably never have to call this method directly.
  49203. */
  49204. virtual void deleteContext() = 0;
  49205. /** Returns the context that's currently in active use by the calling thread.
  49206. Returns 0 if there isn't an active context.
  49207. */
  49208. static OpenGLContext* getCurrentContext();
  49209. protected:
  49210. OpenGLContext() noexcept;
  49211. private:
  49212. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLContext);
  49213. };
  49214. /**
  49215. A component that contains an OpenGL canvas.
  49216. Override this, add it to whatever component you want to, and use the renderOpenGL()
  49217. method to draw its contents.
  49218. */
  49219. class JUCE_API OpenGLComponent : public Component
  49220. {
  49221. public:
  49222. /** Used to select the type of openGL API to use, if more than one choice is available
  49223. on a particular platform.
  49224. */
  49225. enum OpenGLType
  49226. {
  49227. openGLDefault = 0,
  49228. #if JUCE_IOS
  49229. openGLES1, /**< On the iPhone, this selects openGL ES 1.0 */
  49230. openGLES2 /**< On the iPhone, this selects openGL ES 2.0 */
  49231. #endif
  49232. };
  49233. /** Creates an OpenGLComponent.
  49234. If useBackgroundThread is true, the component will launch a background thread
  49235. to do the rendering. If false, then renderOpenGL() will be called as part of the
  49236. normal paint() method.
  49237. */
  49238. OpenGLComponent (OpenGLType type = openGLDefault,
  49239. bool useBackgroundThread = false);
  49240. /** Destructor. */
  49241. ~OpenGLComponent();
  49242. /** Changes the pixel format used by this component.
  49243. @see OpenGLPixelFormat::getAvailablePixelFormats()
  49244. */
  49245. void setPixelFormat (const OpenGLPixelFormat& formatToUse);
  49246. /** Returns the pixel format that this component is currently using. */
  49247. const OpenGLPixelFormat getPixelFormat() const;
  49248. /** Specifies an OpenGL context which should be shared with the one that this
  49249. component is using.
  49250. This is an OpenGL feature that lets two contexts share their texture data.
  49251. Note that this pointer is stored by the component, and when the component
  49252. needs to recreate its internal context for some reason, the same context
  49253. will be used again to share lists. So if you pass a context in here,
  49254. don't delete the context while this component is still using it! You can
  49255. call shareWith (nullptr) to stop this component from sharing with it.
  49256. */
  49257. void shareWith (OpenGLContext* contextToShareListsWith);
  49258. /** Returns the context that this component is sharing with.
  49259. @see shareWith
  49260. */
  49261. OpenGLContext* getShareContext() const noexcept { return contextToShareListsWith; }
  49262. /** Flips the openGL buffers over. */
  49263. void swapBuffers();
  49264. /** Returns true if the component is performing the rendering on a background thread.
  49265. This property is specified in the constructor.
  49266. */
  49267. bool isUsingDedicatedThread() const noexcept { return useThread; }
  49268. /** This replaces the normal paint() callback - use it to draw your openGL stuff.
  49269. When this is called, makeCurrentContextActive() will already have been called
  49270. for you, so you just need to draw.
  49271. */
  49272. virtual void renderOpenGL() = 0;
  49273. /** This method is called when the component creates a new OpenGL context.
  49274. A new context may be created when the component is first used, or when it
  49275. is moved to a different window, or when the window is hidden and re-shown,
  49276. etc.
  49277. You can use this callback as an opportunity to set up things like textures
  49278. that your context needs.
  49279. New contexts are created on-demand by the makeCurrentContextActive() method - so
  49280. if the context is deleted, e.g. by changing the pixel format or window, no context
  49281. will be created until the next call to makeCurrentContextActive(), which will
  49282. synchronously create one and call this method. This means that if you're using
  49283. a non-GUI thread for rendering, you can make sure this method is be called by
  49284. your renderer thread.
  49285. When this callback happens, the context will already have been made current
  49286. using the makeCurrentContextActive() method, so there's no need to call it
  49287. again in your code.
  49288. */
  49289. virtual void newOpenGLContextCreated() = 0;
  49290. /** This method is called when the component shuts down its OpenGL context.
  49291. You can use this callback to delete textures and any other OpenGL objects you
  49292. created in the component's context. Be aware: if you are using a render
  49293. thread, this may be called on the thread.
  49294. When this callback happens, the context will have been made current
  49295. using the makeCurrentContextActive() method, so there's no need to call it
  49296. again in your code.
  49297. */
  49298. virtual void releaseOpenGLContext() {}
  49299. /** Returns the context that will draw into this component.
  49300. This may return 0 if the component is currently invisible or hasn't currently
  49301. got a context. The context object can be deleted and a new one created during
  49302. the lifetime of this component, and there may be times when it doesn't have one.
  49303. @see newOpenGLContextCreated()
  49304. */
  49305. OpenGLContext* getCurrentContext() const noexcept { return context; }
  49306. /** Makes this component the current openGL context.
  49307. You might want to use this in things like your resize() method, before calling
  49308. GL commands.
  49309. If this returns false, then the context isn't active, so you should avoid
  49310. making any calls.
  49311. This call may actually create a context if one isn't currently initialised. If
  49312. it does this, it will also synchronously call the newOpenGLContextCreated()
  49313. method to let you initialise it as necessary.
  49314. @see OpenGLContext::makeActive
  49315. */
  49316. bool makeCurrentContextActive();
  49317. /** Stops the current component being the active OpenGL context.
  49318. This is the opposite of makeCurrentContextActive()
  49319. @see OpenGLContext::makeInactive
  49320. */
  49321. void makeCurrentContextInactive();
  49322. /** Returns true if this component's context is the active openGL context for the
  49323. current thread.
  49324. @see OpenGLContext::isActive
  49325. */
  49326. bool isActiveContext() const noexcept;
  49327. /** Calls the rendering callback, and swaps the buffers afterwards.
  49328. This is called automatically by paint() when the component needs to be rendered.
  49329. Returns true if the operation succeeded.
  49330. */
  49331. virtual bool renderAndSwapBuffers();
  49332. /** This returns a critical section that can be used to lock the current context.
  49333. Because the context that is used by this component can change, e.g. when the
  49334. component is shown or hidden, then if you're rendering to it on a background
  49335. thread, this allows you to lock the context for the duration of your rendering
  49336. routine.
  49337. */
  49338. CriticalSection& getContextLock() noexcept { return contextLock; }
  49339. /** Delete the context.
  49340. You should only need to call this if you've written a custom thread - if so, make
  49341. sure that your thread calls this before it terminates.
  49342. */
  49343. void deleteContext();
  49344. /** Returns the native handle of an embedded heavyweight window, if there is one.
  49345. E.g. On windows, this will return the HWND of the sub-window containing
  49346. the opengl context, on the mac it'll be the NSOpenGLView.
  49347. */
  49348. void* getNativeWindowHandle() const;
  49349. protected:
  49350. /** Kicks off a thread to start rendering.
  49351. The default implementation creates and manages an internal thread that tries
  49352. to render at around 50fps, but this can be overloaded to create a custom thread.
  49353. */
  49354. virtual void startRenderThread();
  49355. /** Cleans up the rendering thread.
  49356. Used to shut down the thread that was started by startRenderThread(). If you've
  49357. created a custom thread, then you should overload this to clean it up and delete it.
  49358. */
  49359. virtual void stopRenderThread();
  49360. /** @internal */
  49361. void paint (Graphics& g);
  49362. private:
  49363. const OpenGLType type;
  49364. class OpenGLComponentRenderThread;
  49365. friend class OpenGLComponentRenderThread;
  49366. friend class ScopedPointer <OpenGLComponentRenderThread>;
  49367. ScopedPointer <OpenGLComponentRenderThread> renderThread;
  49368. class OpenGLComponentWatcher;
  49369. friend class OpenGLComponentWatcher;
  49370. friend class ScopedPointer <OpenGLComponentWatcher>;
  49371. ScopedPointer <OpenGLComponentWatcher> componentWatcher;
  49372. ScopedPointer <OpenGLContext> context;
  49373. OpenGLContext* contextToShareListsWith;
  49374. CriticalSection contextLock;
  49375. OpenGLPixelFormat preferredPixelFormat;
  49376. bool needToUpdateViewport, needToDeleteContext, threadStarted;
  49377. const bool useThread;
  49378. OpenGLContext* createContext();
  49379. void updateContext();
  49380. void updateContextPosition();
  49381. void stopBackgroundThread();
  49382. void recreateContextAsync();
  49383. void internalRepaint (int x, int y, int w, int h);
  49384. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLComponent);
  49385. };
  49386. #endif
  49387. #endif // __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  49388. /*** End of inlined file: juce_OpenGLComponent.h ***/
  49389. #endif
  49390. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  49391. /*** Start of inlined file: juce_PreferencesPanel.h ***/
  49392. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  49393. #define __JUCE_PREFERENCESPANEL_JUCEHEADER__
  49394. /**
  49395. A component with a set of buttons at the top for changing between pages of
  49396. preferences.
  49397. This is just a handy way of writing a Mac-style preferences panel where you
  49398. have a row of buttons along the top for the different preference categories,
  49399. each button having an icon above its name. Clicking these will show an
  49400. appropriate prefs page below it.
  49401. You can either put one of these inside your own component, or just use the
  49402. showInDialogBox() method to show it in a window and run it modally.
  49403. To use it, just add a set of named pages with the addSettingsPage() method,
  49404. and implement the createComponentForPage() method to create suitable components
  49405. for each of these pages.
  49406. */
  49407. class JUCE_API PreferencesPanel : public Component,
  49408. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  49409. {
  49410. public:
  49411. /** Creates an empty panel.
  49412. Use addSettingsPage() to add some pages to it in your constructor.
  49413. */
  49414. PreferencesPanel();
  49415. /** Destructor. */
  49416. ~PreferencesPanel();
  49417. /** Creates a page using a set of drawables to define the page's icon.
  49418. Note that the other version of this method is much easier if you're using
  49419. an image instead of a custom drawable.
  49420. @param pageTitle the name of this preferences page - you'll need to
  49421. make sure your createComponentForPage() method creates
  49422. a suitable component when it is passed this name
  49423. @param normalIcon the drawable to display in the page's button normally
  49424. @param overIcon the drawable to display in the page's button when the mouse is over
  49425. @param downIcon the drawable to display in the page's button when the button is down
  49426. @see DrawableButton
  49427. */
  49428. void addSettingsPage (const String& pageTitle,
  49429. const Drawable* normalIcon,
  49430. const Drawable* overIcon,
  49431. const Drawable* downIcon);
  49432. /** Creates a page using a set of drawables to define the page's icon.
  49433. The other version of this method gives you more control over the icon, but this
  49434. one is much easier if you're just loading it from a file.
  49435. @param pageTitle the name of this preferences page - you'll need to
  49436. make sure your createComponentForPage() method creates
  49437. a suitable component when it is passed this name
  49438. @param imageData a block of data containing an image file, e.g. a jpeg, png or gif.
  49439. For this to look good, you'll probably want to use a nice
  49440. transparent png file.
  49441. @param imageDataSize the size of the image data, in bytes
  49442. */
  49443. void addSettingsPage (const String& pageTitle,
  49444. const void* imageData,
  49445. int imageDataSize);
  49446. /** Utility method to display this panel in a DialogWindow.
  49447. Calling this will create a DialogWindow containing this panel with the
  49448. given size and title, and will run it modally, returning when the user
  49449. closes the dialog box.
  49450. */
  49451. void showInDialogBox (const String& dialogTitle,
  49452. int dialogWidth,
  49453. int dialogHeight,
  49454. const Colour& backgroundColour = Colours::white);
  49455. /** Subclasses must override this to return a component for each preferences page.
  49456. The subclass should return a pointer to a new component representing the named
  49457. page, which the panel will then display.
  49458. The panel will delete the component later when the user goes to another page
  49459. or deletes the panel.
  49460. */
  49461. virtual Component* createComponentForPage (const String& pageName) = 0;
  49462. /** Changes the current page being displayed. */
  49463. void setCurrentPage (const String& pageName);
  49464. /** Returns the size of the buttons shown along the top. */
  49465. int getButtonSize() const noexcept;
  49466. /** Changes the size of the buttons shown along the top. */
  49467. void setButtonSize (int newSize);
  49468. /** @internal */
  49469. void resized();
  49470. /** @internal */
  49471. void paint (Graphics& g);
  49472. /** @internal */
  49473. void buttonClicked (Button* button);
  49474. private:
  49475. String currentPageName;
  49476. ScopedPointer <Component> currentPage;
  49477. OwnedArray<DrawableButton> buttons;
  49478. int buttonSize;
  49479. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PreferencesPanel);
  49480. };
  49481. #endif // __JUCE_PREFERENCESPANEL_JUCEHEADER__
  49482. /*** End of inlined file: juce_PreferencesPanel.h ***/
  49483. #endif
  49484. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  49485. /*** Start of inlined file: juce_QuickTimeMovieComponent.h ***/
  49486. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  49487. #define __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  49488. // (NB: This stuff mustn't go inside the "#if QUICKTIME" block, or it'll break the
  49489. // amalgamated build)
  49490. #ifndef DOXYGEN
  49491. #if JUCE_WINDOWS
  49492. typedef ActiveXControlComponent QTCompBaseClass;
  49493. #elif JUCE_MAC
  49494. typedef NSViewComponent QTCompBaseClass;
  49495. #endif
  49496. #endif
  49497. // this is used to disable QuickTime, and is defined in juce_Config.h
  49498. #if JUCE_QUICKTIME || DOXYGEN
  49499. /**
  49500. A window that can play back a QuickTime movie.
  49501. */
  49502. class JUCE_API QuickTimeMovieComponent : public QTCompBaseClass
  49503. {
  49504. public:
  49505. /** Creates a QuickTimeMovieComponent, initially blank.
  49506. Use the loadMovie() method to load a movie once you've added the
  49507. component to a window, (or put it on the desktop as a heavyweight window).
  49508. Loading a movie when the component isn't visible can cause problems, as
  49509. QuickTime needs a window handle to initialise properly.
  49510. */
  49511. QuickTimeMovieComponent();
  49512. /** Destructor. */
  49513. ~QuickTimeMovieComponent();
  49514. /** Returns true if QT is installed and working on this machine.
  49515. */
  49516. static bool isQuickTimeAvailable() noexcept;
  49517. /** Tries to load a QuickTime movie from a file into the player.
  49518. It's best to call this function once you've added the component to a window,
  49519. (or put it on the desktop as a heavyweight window). Loading a movie when the
  49520. component isn't visible can cause problems, because QuickTime needs a window
  49521. handle to do its stuff.
  49522. @param movieFile the .mov file to open
  49523. @param isControllerVisible whether to show a controller bar at the bottom
  49524. @returns true if the movie opens successfully
  49525. */
  49526. bool loadMovie (const File& movieFile,
  49527. bool isControllerVisible);
  49528. /** Tries to load a QuickTime movie from a URL into the player.
  49529. It's best to call this function once you've added the component to a window,
  49530. (or put it on the desktop as a heavyweight window). Loading a movie when the
  49531. component isn't visible can cause problems, because QuickTime needs a window
  49532. handle to do its stuff.
  49533. @param movieURL the .mov file to open
  49534. @param isControllerVisible whether to show a controller bar at the bottom
  49535. @returns true if the movie opens successfully
  49536. */
  49537. bool loadMovie (const URL& movieURL,
  49538. bool isControllerVisible);
  49539. /** Tries to load a QuickTime movie from a stream into the player.
  49540. It's best to call this function once you've added the component to a window,
  49541. (or put it on the desktop as a heavyweight window). Loading a movie when the
  49542. component isn't visible can cause problems, because QuickTime needs a window
  49543. handle to do its stuff.
  49544. @param movieStream a stream containing a .mov file. The component may try
  49545. to read the whole stream before playing, rather than
  49546. streaming from it.
  49547. @param isControllerVisible whether to show a controller bar at the bottom
  49548. @returns true if the movie opens successfully
  49549. */
  49550. bool loadMovie (InputStream* movieStream,
  49551. bool isControllerVisible);
  49552. /** Closes the movie, if one is open. */
  49553. void closeMovie();
  49554. /** Returns the movie file that is currently open.
  49555. If there isn't one, this returns File::nonexistent
  49556. */
  49557. File getCurrentMovieFile() const;
  49558. /** Returns true if there's currently a movie open. */
  49559. bool isMovieOpen() const;
  49560. /** Returns the length of the movie, in seconds. */
  49561. double getMovieDuration() const;
  49562. /** Returns the movie's natural size, in pixels.
  49563. You can use this to resize the component to show the movie at its preferred
  49564. scale.
  49565. If no movie is loaded, the size returned will be 0 x 0.
  49566. */
  49567. void getMovieNormalSize (int& width, int& height) const;
  49568. /** This will position the component within a given area, keeping its aspect
  49569. ratio correct according to the movie's normal size.
  49570. The component will be made as large as it can go within the space, and will
  49571. be aligned according to the justification value if this means there are gaps at
  49572. the top or sides.
  49573. */
  49574. void setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  49575. const RectanglePlacement& placement);
  49576. /** Starts the movie playing. */
  49577. void play();
  49578. /** Stops the movie playing. */
  49579. void stop();
  49580. /** Returns true if the movie is currently playing. */
  49581. bool isPlaying() const;
  49582. /** Moves the movie's position back to the start. */
  49583. void goToStart();
  49584. /** Sets the movie's position to a given time. */
  49585. void setPosition (double seconds);
  49586. /** Returns the current play position of the movie. */
  49587. double getPosition() const;
  49588. /** Changes the movie playback rate.
  49589. A value of 1 is normal speed, greater values play it proportionately faster,
  49590. smaller values play it slower.
  49591. */
  49592. void setSpeed (float newSpeed);
  49593. /** Changes the movie's playback volume.
  49594. @param newVolume the volume in the range 0 (silent) to 1.0 (full)
  49595. */
  49596. void setMovieVolume (float newVolume);
  49597. /** Returns the movie's playback volume.
  49598. @returns the volume in the range 0 (silent) to 1.0 (full)
  49599. */
  49600. float getMovieVolume() const;
  49601. /** Tells the movie whether it should loop. */
  49602. void setLooping (bool shouldLoop);
  49603. /** Returns true if the movie is currently looping.
  49604. @see setLooping
  49605. */
  49606. bool isLooping() const;
  49607. /** True if the native QuickTime controller bar is shown in the window.
  49608. @see loadMovie
  49609. */
  49610. bool isControllerVisible() const;
  49611. /** @internal */
  49612. void paint (Graphics& g);
  49613. private:
  49614. File movieFile;
  49615. bool movieLoaded, controllerVisible, looping;
  49616. #if JUCE_WINDOWS
  49617. void parentHierarchyChanged();
  49618. void visibilityChanged();
  49619. void createControlIfNeeded();
  49620. bool isControlCreated() const;
  49621. class Pimpl;
  49622. friend class ScopedPointer <Pimpl>;
  49623. ScopedPointer <Pimpl> pimpl;
  49624. #else
  49625. void* movie;
  49626. #endif
  49627. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (QuickTimeMovieComponent);
  49628. };
  49629. #endif
  49630. #endif // __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  49631. /*** End of inlined file: juce_QuickTimeMovieComponent.h ***/
  49632. #endif
  49633. #ifndef __JUCE_SCOPEDXLOCK_JUCEHEADER__
  49634. /*** Start of inlined file: juce_ScopedXLock.h ***/
  49635. #ifndef __JUCE_SCOPEDXLOCK_JUCEHEADER__
  49636. #define __JUCE_SCOPEDXLOCK_JUCEHEADER__
  49637. #if JUCE_LINUX || DOXYGEN
  49638. /** A handy class that uses XLockDisplay and XUnlockDisplay to lock the X server
  49639. using RAII (Only available in Linux!).
  49640. */
  49641. class ScopedXLock
  49642. {
  49643. public:
  49644. /** Creating a ScopedXLock object locks the X display.
  49645. This uses XLockDisplay() to grab the display that Juce is using.
  49646. */
  49647. ScopedXLock();
  49648. /** Deleting a ScopedXLock object unlocks the X display.
  49649. This calls XUnlockDisplay() to release the lock.
  49650. */
  49651. ~ScopedXLock();
  49652. };
  49653. #endif
  49654. #endif // __JUCE_SCOPEDXLOCK_JUCEHEADER__
  49655. /*** End of inlined file: juce_ScopedXLock.h ***/
  49656. #endif
  49657. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  49658. /*** Start of inlined file: juce_SystemTrayIconComponent.h ***/
  49659. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  49660. #define __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  49661. #if JUCE_WINDOWS || JUCE_LINUX || DOXYGEN
  49662. /**
  49663. On Windows only, this component sits in the taskbar tray as a small icon.
  49664. To use it, just create one of these components, but don't attempt to make it
  49665. visible, add it to a parent, or put it on the desktop.
  49666. You can then call setIconImage() to create an icon for it in the taskbar.
  49667. To change the icon's tooltip, you can use setIconTooltip().
  49668. To respond to mouse-events, you can override the normal mouseDown(),
  49669. mouseUp(), mouseDoubleClick() and mouseMove() methods, and although the x, y
  49670. position will not be valid, you can use this to respond to clicks. Traditionally
  49671. you'd use a left-click to show your application's window, and a right-click
  49672. to show a pop-up menu.
  49673. */
  49674. class JUCE_API SystemTrayIconComponent : public Component
  49675. {
  49676. public:
  49677. SystemTrayIconComponent();
  49678. /** Destructor. */
  49679. ~SystemTrayIconComponent();
  49680. /** Changes the image shown in the taskbar.
  49681. */
  49682. void setIconImage (const Image& newImage);
  49683. /** Changes the tooltip that Windows shows above the icon. */
  49684. void setIconTooltip (const String& tooltip);
  49685. #if JUCE_LINUX
  49686. /** @internal */
  49687. void paint (Graphics& g);
  49688. #endif
  49689. private:
  49690. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SystemTrayIconComponent);
  49691. };
  49692. #endif
  49693. #endif // __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  49694. /*** End of inlined file: juce_SystemTrayIconComponent.h ***/
  49695. #endif
  49696. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  49697. /*** Start of inlined file: juce_WebBrowserComponent.h ***/
  49698. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  49699. #define __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  49700. #if JUCE_WEB_BROWSER || DOXYGEN
  49701. #if ! DOXYGEN
  49702. class WebBrowserComponentInternal;
  49703. #endif
  49704. /**
  49705. A component that displays an embedded web browser.
  49706. The browser itself will be platform-dependent. On the Mac, probably Safari, on
  49707. Windows, probably IE.
  49708. */
  49709. class JUCE_API WebBrowserComponent : public Component
  49710. {
  49711. public:
  49712. /** Creates a WebBrowserComponent.
  49713. Once it's created and visible, send the browser to a URL using goToURL().
  49714. @param unloadPageWhenBrowserIsHidden if this is true, then when the browser
  49715. component is taken offscreen, it'll clear the current page
  49716. and replace it with a blank page - this can be handy to stop
  49717. the browser using resources in the background when it's not
  49718. actually being used.
  49719. */
  49720. explicit WebBrowserComponent (bool unloadPageWhenBrowserIsHidden = true);
  49721. /** Destructor. */
  49722. ~WebBrowserComponent();
  49723. /** Sends the browser to a particular URL.
  49724. @param url the URL to go to.
  49725. @param headers an optional set of parameters to put in the HTTP header. If
  49726. you supply this, it should be a set of string in the form
  49727. "HeaderKey: HeaderValue"
  49728. @param postData an optional block of data that will be attached to the HTTP
  49729. POST request
  49730. */
  49731. void goToURL (const String& url,
  49732. const StringArray* headers = nullptr,
  49733. const MemoryBlock* postData = nullptr);
  49734. /** Stops the current page loading.
  49735. */
  49736. void stop();
  49737. /** Sends the browser back one page.
  49738. */
  49739. void goBack();
  49740. /** Sends the browser forward one page.
  49741. */
  49742. void goForward();
  49743. /** Refreshes the browser.
  49744. */
  49745. void refresh();
  49746. /** This callback is called when the browser is about to navigate
  49747. to a new location.
  49748. You can override this method to perform some action when the user
  49749. tries to go to a particular URL. To allow the operation to carry on,
  49750. return true, or return false to stop the navigation happening.
  49751. */
  49752. virtual bool pageAboutToLoad (const String& newURL);
  49753. /** @internal */
  49754. void paint (Graphics& g);
  49755. /** @internal */
  49756. void resized();
  49757. /** @internal */
  49758. void parentHierarchyChanged();
  49759. /** @internal */
  49760. void visibilityChanged();
  49761. private:
  49762. WebBrowserComponentInternal* browser;
  49763. bool blankPageShown, unloadPageWhenBrowserIsHidden;
  49764. String lastURL;
  49765. StringArray lastHeaders;
  49766. MemoryBlock lastPostData;
  49767. void reloadLastURL();
  49768. void checkWindowAssociation();
  49769. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebBrowserComponent);
  49770. };
  49771. #endif
  49772. #endif // __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  49773. /*** End of inlined file: juce_WebBrowserComponent.h ***/
  49774. #endif
  49775. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  49776. #endif
  49777. #ifndef __JUCE_CALLOUTBOX_JUCEHEADER__
  49778. /*** Start of inlined file: juce_CallOutBox.h ***/
  49779. #ifndef __JUCE_CALLOUTBOX_JUCEHEADER__
  49780. #define __JUCE_CALLOUTBOX_JUCEHEADER__
  49781. /**
  49782. A box with a small arrow that can be used as a temporary pop-up window to show
  49783. extra controls when a button or other component is clicked.
  49784. Using one of these is similar to having a popup menu attached to a button or
  49785. other component - but it looks fancier, and has an arrow that can indicate the
  49786. object that it applies to.
  49787. Normally, you'd create one of these on the stack and run it modally, e.g.
  49788. @code
  49789. void mouseUp (const MouseEvent& e)
  49790. {
  49791. MyContentComponent content;
  49792. content.setSize (300, 300);
  49793. CallOutBox callOut (content, *this, nullptr);
  49794. callOut.runModalLoop();
  49795. }
  49796. @endcode
  49797. The call-out will resize and position itself when the content changes size.
  49798. */
  49799. class JUCE_API CallOutBox : public Component
  49800. {
  49801. public:
  49802. /** Creates a CallOutBox.
  49803. @param contentComponent the component to display inside the call-out. This should
  49804. already have a size set (although the call-out will also
  49805. update itself when the component's size is changed later).
  49806. Obviously this component must not be deleted until the
  49807. call-out box has been deleted.
  49808. @param componentToPointTo the component that the call-out's arrow should point towards
  49809. @param parentComponent if non-zero, this is the component to add the call-out to. If
  49810. this is zero, the call-out will be added to the desktop.
  49811. */
  49812. CallOutBox (Component& contentComponent,
  49813. Component& componentToPointTo,
  49814. Component* parentComponent);
  49815. /** Destructor. */
  49816. ~CallOutBox();
  49817. /** Changes the length of the arrow. */
  49818. void setArrowSize (float newSize);
  49819. /** Updates the position and size of the box.
  49820. You shouldn't normally need to call this, unless you need more precise control over the
  49821. layout.
  49822. @param newAreaToPointTo the rectangle to make the box's arrow point to
  49823. @param newAreaToFitIn the area within which the box's position should be constrained
  49824. */
  49825. void updatePosition (const Rectangle<int>& newAreaToPointTo,
  49826. const Rectangle<int>& newAreaToFitIn);
  49827. /** @internal */
  49828. void paint (Graphics& g);
  49829. /** @internal */
  49830. void resized();
  49831. /** @internal */
  49832. void moved();
  49833. /** @internal */
  49834. void childBoundsChanged (Component*);
  49835. /** @internal */
  49836. bool hitTest (int x, int y);
  49837. /** @internal */
  49838. void inputAttemptWhenModal();
  49839. /** @internal */
  49840. bool keyPressed (const KeyPress& key);
  49841. /** @internal */
  49842. void handleCommandMessage (int commandId);
  49843. private:
  49844. int borderSpace;
  49845. float arrowSize;
  49846. Component& content;
  49847. Path outline;
  49848. Point<float> targetPoint;
  49849. Rectangle<int> availableArea, targetArea;
  49850. Image background;
  49851. void refreshPath();
  49852. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CallOutBox);
  49853. };
  49854. #endif // __JUCE_CALLOUTBOX_JUCEHEADER__
  49855. /*** End of inlined file: juce_CallOutBox.h ***/
  49856. #endif
  49857. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  49858. /*** Start of inlined file: juce_ComponentPeer.h ***/
  49859. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  49860. #define __JUCE_COMPONENTPEER_JUCEHEADER__
  49861. class ComponentBoundsConstrainer;
  49862. /**
  49863. The Component class uses a ComponentPeer internally to create and manage a real
  49864. operating-system window.
  49865. This is an abstract base class - the platform specific code contains implementations of
  49866. it for the various platforms.
  49867. User-code should very rarely need to have any involvement with this class.
  49868. @see Component::createNewPeer
  49869. */
  49870. class JUCE_API ComponentPeer
  49871. {
  49872. public:
  49873. /** A combination of these flags is passed to the ComponentPeer constructor. */
  49874. enum StyleFlags
  49875. {
  49876. windowAppearsOnTaskbar = (1 << 0), /**< Indicates that the window should have a corresponding
  49877. entry on the taskbar (ignored on MacOSX) */
  49878. windowIsTemporary = (1 << 1), /**< Indicates that the window is a temporary popup, like a menu,
  49879. tooltip, etc. */
  49880. windowIgnoresMouseClicks = (1 << 2), /**< Indicates that the window should let mouse clicks pass
  49881. through it (may not be possible on some platforms). */
  49882. windowHasTitleBar = (1 << 3), /**< Indicates that the window should have a normal OS-specific
  49883. title bar and frame\. if not specified, the window will be
  49884. borderless. */
  49885. windowIsResizable = (1 << 4), /**< Indicates that the window should have a resizable border. */
  49886. windowHasMinimiseButton = (1 << 5), /**< Indicates that if the window has a title bar, it should have a
  49887. minimise button on it. */
  49888. windowHasMaximiseButton = (1 << 6), /**< Indicates that if the window has a title bar, it should have a
  49889. maximise button on it. */
  49890. windowHasCloseButton = (1 << 7), /**< Indicates that if the window has a title bar, it should have a
  49891. close button on it. */
  49892. windowHasDropShadow = (1 << 8), /**< Indicates that the window should have a drop-shadow (this may
  49893. not be possible on all platforms). */
  49894. windowRepaintedExplictly = (1 << 9), /**< Not intended for public use - this tells a window not to
  49895. do its own repainting, but only to repaint when the
  49896. performAnyPendingRepaintsNow() method is called. */
  49897. windowIgnoresKeyPresses = (1 << 10), /**< Tells the window not to catch any keypresses. This can
  49898. be used for things like plugin windows, to stop them interfering
  49899. with the host's shortcut keys */
  49900. windowIsSemiTransparent = (1 << 31) /**< Not intended for public use - makes a window transparent. */
  49901. };
  49902. /** Creates a peer.
  49903. The component is the one that we intend to represent, and the style flags are
  49904. a combination of the values in the StyleFlags enum
  49905. */
  49906. ComponentPeer (Component* component, int styleFlags);
  49907. /** Destructor. */
  49908. virtual ~ComponentPeer();
  49909. /** Returns the component being represented by this peer. */
  49910. Component* getComponent() const noexcept { return component; }
  49911. /** Returns the set of style flags that were set when the window was created.
  49912. @see Component::addToDesktop
  49913. */
  49914. int getStyleFlags() const noexcept { return styleFlags; }
  49915. /** Returns a unique ID for this peer.
  49916. Each peer that is created is given a different ID.
  49917. */
  49918. uint32 getUniqueID() const noexcept { return uniqueID; }
  49919. /** Returns the raw handle to whatever kind of window is being used.
  49920. On windows, this is probably a HWND, on the mac, it's likely to be a WindowRef,
  49921. but rememeber there's no guarantees what you'll get back.
  49922. */
  49923. virtual void* getNativeHandle() const = 0;
  49924. /** Shows or hides the window. */
  49925. virtual void setVisible (bool shouldBeVisible) = 0;
  49926. /** Changes the title of the window. */
  49927. virtual void setTitle (const String& title) = 0;
  49928. /** Moves the window without changing its size.
  49929. If the native window is contained in another window, then the co-ordinates are
  49930. relative to the parent window's origin, not the screen origin.
  49931. This should result in a callback to handleMovedOrResized().
  49932. */
  49933. virtual void setPosition (int x, int y) = 0;
  49934. /** Resizes the window without changing its position.
  49935. This should result in a callback to handleMovedOrResized().
  49936. */
  49937. virtual void setSize (int w, int h) = 0;
  49938. /** Moves and resizes the window.
  49939. If the native window is contained in another window, then the co-ordinates are
  49940. relative to the parent window's origin, not the screen origin.
  49941. This should result in a callback to handleMovedOrResized().
  49942. */
  49943. virtual void setBounds (int x, int y, int w, int h, bool isNowFullScreen) = 0;
  49944. /** Returns the current position and size of the window.
  49945. If the native window is contained in another window, then the co-ordinates are
  49946. relative to the parent window's origin, not the screen origin.
  49947. */
  49948. virtual const Rectangle<int> getBounds() const = 0;
  49949. /** Returns the x-position of this window, relative to the screen's origin. */
  49950. virtual const Point<int> getScreenPosition() const = 0;
  49951. /** Converts a position relative to the top-left of this component to screen co-ordinates. */
  49952. virtual const Point<int> localToGlobal (const Point<int>& relativePosition) = 0;
  49953. /** Converts a rectangle relative to the top-left of this component to screen co-ordinates. */
  49954. virtual const Rectangle<int> localToGlobal (const Rectangle<int>& relativePosition);
  49955. /** Converts a screen co-ordinate to a position relative to the top-left of this component. */
  49956. virtual const Point<int> globalToLocal (const Point<int>& screenPosition) = 0;
  49957. /** Converts a screen area to a position relative to the top-left of this component. */
  49958. virtual const Rectangle<int> globalToLocal (const Rectangle<int>& screenPosition);
  49959. /** Minimises the window. */
  49960. virtual void setMinimised (bool shouldBeMinimised) = 0;
  49961. /** True if the window is currently minimised. */
  49962. virtual bool isMinimised() const = 0;
  49963. /** Enable/disable fullscreen mode for the window. */
  49964. virtual void setFullScreen (bool shouldBeFullScreen) = 0;
  49965. /** True if the window is currently full-screen. */
  49966. virtual bool isFullScreen() const = 0;
  49967. /** Sets the size to restore to if fullscreen mode is turned off. */
  49968. void setNonFullScreenBounds (const Rectangle<int>& newBounds) noexcept;
  49969. /** Returns the size to restore to if fullscreen mode is turned off. */
  49970. const Rectangle<int>& getNonFullScreenBounds() const noexcept;
  49971. /** Attempts to change the icon associated with this window.
  49972. */
  49973. virtual void setIcon (const Image& newIcon) = 0;
  49974. /** Sets a constrainer to use if the peer can resize itself.
  49975. The constrainer won't be deleted by this object, so the caller must manage its lifetime.
  49976. */
  49977. void setConstrainer (ComponentBoundsConstrainer* newConstrainer) noexcept;
  49978. /** Returns the current constrainer, if one has been set. */
  49979. ComponentBoundsConstrainer* getConstrainer() const noexcept { return constrainer; }
  49980. /** Checks if a point is in the window.
  49981. Coordinates are relative to the top-left of this window. If trueIfInAChildWindow
  49982. is false, then this returns false if the point is actually inside a child of this
  49983. window.
  49984. */
  49985. virtual bool contains (const Point<int>& position, bool trueIfInAChildWindow) const = 0;
  49986. /** Returns the size of the window frame that's around this window.
  49987. Whether or not the window has a normal window frame depends on the flags
  49988. that were set when the window was created by Component::addToDesktop()
  49989. */
  49990. virtual const BorderSize<int> getFrameSize() const = 0;
  49991. /** This is called when the window's bounds change.
  49992. A peer implementation must call this when the window is moved and resized, so that
  49993. this method can pass the message on to the component.
  49994. */
  49995. void handleMovedOrResized();
  49996. /** This is called if the screen resolution changes.
  49997. A peer implementation must call this if the monitor arrangement changes or the available
  49998. screen size changes.
  49999. */
  50000. void handleScreenSizeChange();
  50001. /** This is called to repaint the component into the given context. */
  50002. void handlePaint (LowLevelGraphicsContext& contextToPaintTo);
  50003. /** Sets this window to either be always-on-top or normal.
  50004. Some kinds of window might not be able to do this, so should return false.
  50005. */
  50006. virtual bool setAlwaysOnTop (bool alwaysOnTop) = 0;
  50007. /** Brings the window to the top, optionally also giving it focus. */
  50008. virtual void toFront (bool makeActive) = 0;
  50009. /** Moves the window to be just behind another one. */
  50010. virtual void toBehind (ComponentPeer* other) = 0;
  50011. /** Called when the window is brought to the front, either by the OS or by a call
  50012. to toFront().
  50013. */
  50014. void handleBroughtToFront();
  50015. /** True if the window has the keyboard focus. */
  50016. virtual bool isFocused() const = 0;
  50017. /** Tries to give the window keyboard focus. */
  50018. virtual void grabFocus() = 0;
  50019. /** Called when the window gains keyboard focus. */
  50020. void handleFocusGain();
  50021. /** Called when the window loses keyboard focus. */
  50022. void handleFocusLoss();
  50023. Component* getLastFocusedSubcomponent() const noexcept;
  50024. /** Called when a key is pressed.
  50025. For keycode info, see the KeyPress class.
  50026. Returns true if the keystroke was used.
  50027. */
  50028. bool handleKeyPress (int keyCode, juce_wchar textCharacter);
  50029. /** Called whenever a key is pressed or released.
  50030. Returns true if the keystroke was used.
  50031. */
  50032. bool handleKeyUpOrDown (bool isKeyDown);
  50033. /** Called whenever a modifier key is pressed or released. */
  50034. void handleModifierKeysChange();
  50035. /** Tells the window that text input may be required at the given position.
  50036. This may cause things like a virtual on-screen keyboard to appear, depending
  50037. on the OS.
  50038. */
  50039. virtual void textInputRequired (const Point<int>& position) = 0;
  50040. /** If there's some kind of OS input-method in progress, this should dismiss it. */
  50041. virtual void dismissPendingTextInput();
  50042. /** Returns the currently focused TextInputTarget, or null if none is found. */
  50043. TextInputTarget* findCurrentTextInputTarget();
  50044. /** Invalidates a region of the window to be repainted asynchronously. */
  50045. virtual void repaint (const Rectangle<int>& area) = 0;
  50046. /** This can be called (from the message thread) to cause the immediate redrawing
  50047. of any areas of this window that need repainting.
  50048. You shouldn't ever really need to use this, it's mainly for special purposes
  50049. like supporting audio plugins where the host's event loop is out of our control.
  50050. */
  50051. virtual void performAnyPendingRepaintsNow() = 0;
  50052. /** Changes the window's transparency. */
  50053. virtual void setAlpha (float newAlpha) = 0;
  50054. void handleMouseEvent (int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, int64 time);
  50055. void handleMouseWheel (int touchIndex, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  50056. void handleUserClosingWindow();
  50057. void handleFileDragMove (const StringArray& files, const Point<int>& position);
  50058. void handleFileDragExit (const StringArray& files);
  50059. void handleFileDragDrop (const StringArray& files, const Point<int>& position);
  50060. /** Resets the masking region.
  50061. The subclass should call this every time it's about to call the handlePaint
  50062. method.
  50063. @see addMaskedRegion
  50064. */
  50065. void clearMaskedRegion();
  50066. /** Adds a rectangle to the set of areas not to paint over.
  50067. A component can call this on its peer during its paint() method, to signal
  50068. that the painting code should ignore a given region. The reason
  50069. for this is to stop embedded windows (such as OpenGL) getting painted over.
  50070. The masked region is cleared each time before a paint happens, so a component
  50071. will have to make sure it calls this every time it's painted.
  50072. */
  50073. void addMaskedRegion (int x, int y, int w, int h);
  50074. /** Returns the number of currently-active peers.
  50075. @see getPeer
  50076. */
  50077. static int getNumPeers() noexcept;
  50078. /** Returns one of the currently-active peers.
  50079. @see getNumPeers
  50080. */
  50081. static ComponentPeer* getPeer (int index) noexcept;
  50082. /** Checks if this peer object is valid.
  50083. @see getNumPeers
  50084. */
  50085. static bool isValidPeer (const ComponentPeer* peer) noexcept;
  50086. virtual StringArray getAvailableRenderingEngines();
  50087. virtual int getCurrentRenderingEngine() const;
  50088. virtual void setCurrentRenderingEngine (int index);
  50089. protected:
  50090. Component* const component;
  50091. const int styleFlags;
  50092. RectangleList maskedRegion;
  50093. Rectangle<int> lastNonFullscreenBounds;
  50094. uint32 lastPaintTime;
  50095. ComponentBoundsConstrainer* constrainer;
  50096. static void updateCurrentModifiers() noexcept;
  50097. private:
  50098. WeakReference<Component> lastFocusedComponent, dragAndDropTargetComponent;
  50099. Component* lastDragAndDropCompUnderMouse;
  50100. const uint32 uniqueID;
  50101. bool fakeMouseMessageSent : 1, isWindowMinimised : 1;
  50102. friend class Component;
  50103. friend class Desktop;
  50104. static ComponentPeer* getPeerFor (const Component* component) noexcept;
  50105. void setLastDragDropTarget (Component* comp);
  50106. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentPeer);
  50107. };
  50108. #endif // __JUCE_COMPONENTPEER_JUCEHEADER__
  50109. /*** End of inlined file: juce_ComponentPeer.h ***/
  50110. #endif
  50111. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  50112. /*** Start of inlined file: juce_DialogWindow.h ***/
  50113. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  50114. #define __JUCE_DIALOGWINDOW_JUCEHEADER__
  50115. /**
  50116. A dialog-box style window.
  50117. This class is a convenient way of creating a DocumentWindow with a close button
  50118. that can be triggered by pressing the escape key.
  50119. Any of the methods available to a DocumentWindow or ResizableWindow are also
  50120. available to this, so it can be made resizable, have a menu bar, etc.
  50121. To add items to the box, see the ResizableWindow::setContentOwned() or
  50122. ResizableWindow::setContentNonOwned() methods. Don't add components directly to this
  50123. class - always put them in a content component!
  50124. You'll need to override the DocumentWindow::closeButtonPressed() method to handle
  50125. the user clicking the close button - for more info, see the DocumentWindow
  50126. help.
  50127. @see DocumentWindow, ResizableWindow
  50128. */
  50129. class JUCE_API DialogWindow : public DocumentWindow
  50130. {
  50131. public:
  50132. /** Creates a DialogWindow.
  50133. @param name the name to give the component - this is also
  50134. the title shown at the top of the window. To change
  50135. this later, use setName()
  50136. @param backgroundColour the colour to use for filling the window's background.
  50137. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  50138. close button to be triggered
  50139. @param addToDesktop if true, the window will be automatically added to the
  50140. desktop; if false, you can use it as a child component
  50141. */
  50142. DialogWindow (const String& name,
  50143. const Colour& backgroundColour,
  50144. bool escapeKeyTriggersCloseButton,
  50145. bool addToDesktop = true);
  50146. /** Destructor.
  50147. If a content component has been set with setContentOwned(), it will be deleted.
  50148. */
  50149. ~DialogWindow();
  50150. /** Easy way of quickly showing a dialog box containing a given component.
  50151. This will open and display a DialogWindow containing a given component, making it
  50152. modal, but returning immediately to allow the dialog to finish in its own time. If
  50153. you want to block and run a modal loop until the dialog is dismissed, use showModalDialog()
  50154. instead.
  50155. To close the dialog programatically, you should call exitModalState (returnValue) on
  50156. the DialogWindow that is created. To find a pointer to this window from your
  50157. contentComponent, you can do something like this:
  50158. @code
  50159. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) nullptr);
  50160. if (dw != nullptr)
  50161. dw->exitModalState (1234);
  50162. @endcode
  50163. @param dialogTitle the dialog box's title
  50164. @param contentComponent the content component for the dialog box. Make sure
  50165. that this has been set to the size you want it to
  50166. be before calling this method. The component won't
  50167. be deleted by this call, so you can re-use it or delete
  50168. it afterwards
  50169. @param componentToCentreAround if this is non-zero, it indicates a component that
  50170. you'd like to show this dialog box in front of. See the
  50171. DocumentWindow::centreAroundComponent() method for more
  50172. info on this parameter
  50173. @param backgroundColour a colour to use for the dialog box's background colour
  50174. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  50175. close button to be triggered
  50176. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  50177. a corner resizer
  50178. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  50179. to use a border or corner resizer component. See ResizableWindow::setResizable()
  50180. */
  50181. static void showDialog (const String& dialogTitle,
  50182. Component* contentComponent,
  50183. Component* componentToCentreAround,
  50184. const Colour& backgroundColour,
  50185. bool escapeKeyTriggersCloseButton,
  50186. bool shouldBeResizable = false,
  50187. bool useBottomRightCornerResizer = false);
  50188. /** Easy way of quickly showing a dialog box containing a given component.
  50189. This will open and display a DialogWindow containing a given component, returning
  50190. when the user clicks its close button.
  50191. It returns the value that was returned by the dialog box's runModalLoop() call.
  50192. To close the dialog programatically, you should call exitModalState (returnValue) on
  50193. the DialogWindow that is created. To find a pointer to this window from your
  50194. contentComponent, you can do something like this:
  50195. @code
  50196. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) nullptr);
  50197. if (dw != nullptr)
  50198. dw->exitModalState (1234);
  50199. @endcode
  50200. @param dialogTitle the dialog box's title
  50201. @param contentComponent the content component for the dialog box. Make sure
  50202. that this has been set to the size you want it to
  50203. be before calling this method. The component won't
  50204. be deleted by this call, so you can re-use it or delete
  50205. it afterwards
  50206. @param componentToCentreAround if this is non-zero, it indicates a component that
  50207. you'd like to show this dialog box in front of. See the
  50208. DocumentWindow::centreAroundComponent() method for more
  50209. info on this parameter
  50210. @param backgroundColour a colour to use for the dialog box's background colour
  50211. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  50212. close button to be triggered
  50213. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  50214. a corner resizer
  50215. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  50216. to use a border or corner resizer component. See ResizableWindow::setResizable()
  50217. */
  50218. #if JUCE_MODAL_LOOPS_PERMITTED || DOXYGEN
  50219. static int showModalDialog (const String& dialogTitle,
  50220. Component* contentComponent,
  50221. Component* componentToCentreAround,
  50222. const Colour& backgroundColour,
  50223. bool escapeKeyTriggersCloseButton,
  50224. bool shouldBeResizable = false,
  50225. bool useBottomRightCornerResizer = false);
  50226. #endif
  50227. protected:
  50228. /** @internal */
  50229. void resized();
  50230. private:
  50231. bool escapeKeyTriggersCloseButton;
  50232. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DialogWindow);
  50233. };
  50234. #endif // __JUCE_DIALOGWINDOW_JUCEHEADER__
  50235. /*** End of inlined file: juce_DialogWindow.h ***/
  50236. #endif
  50237. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  50238. #endif
  50239. #ifndef __JUCE_NATIVEMESSAGEBOX_JUCEHEADER__
  50240. /*** Start of inlined file: juce_NativeMessageBox.h ***/
  50241. #ifndef __JUCE_NATIVEMESSAGEBOX_JUCEHEADER__
  50242. #define __JUCE_NATIVEMESSAGEBOX_JUCEHEADER__
  50243. class NativeMessageBox
  50244. {
  50245. public:
  50246. /** Shows a dialog box that just has a message and a single 'ok' button to close it.
  50247. If the callback parameter is null, the box is shown modally, and the method will
  50248. block until the user has clicked the button (or pressed the escape or return keys).
  50249. If the callback parameter is non-null, the box will be displayed and placed into a
  50250. modal state, but this method will return immediately, and the callback will be invoked
  50251. later when the user dismisses the box.
  50252. @param iconType the type of icon to show
  50253. @param title the headline to show at the top of the box
  50254. @param message a longer, more descriptive message to show underneath the title
  50255. @param associatedComponent if this is non-null, it specifies the component that the
  50256. alert window should be associated with. Depending on the look
  50257. and feel, this might be used for positioning of the alert window.
  50258. */
  50259. #if JUCE_MODAL_LOOPS_PERMITTED
  50260. static void JUCE_CALLTYPE showMessageBox (AlertWindow::AlertIconType iconType,
  50261. const String& title,
  50262. const String& message,
  50263. Component* associatedComponent = nullptr);
  50264. #endif
  50265. /** Shows a dialog box that just has a message and a single 'ok' button to close it.
  50266. If the callback parameter is null, the box is shown modally, and the method will
  50267. block until the user has clicked the button (or pressed the escape or return keys).
  50268. If the callback parameter is non-null, the box will be displayed and placed into a
  50269. modal state, but this method will return immediately, and the callback will be invoked
  50270. later when the user dismisses the box.
  50271. @param iconType the type of icon to show
  50272. @param title the headline to show at the top of the box
  50273. @param message a longer, more descriptive message to show underneath the title
  50274. @param associatedComponent if this is non-null, it specifies the component that the
  50275. alert window should be associated with. Depending on the look
  50276. and feel, this might be used for positioning of the alert window.
  50277. */
  50278. static void JUCE_CALLTYPE showMessageBoxAsync (AlertWindow::AlertIconType iconType,
  50279. const String& title,
  50280. const String& message,
  50281. Component* associatedComponent = nullptr);
  50282. /** Shows a dialog box with two buttons.
  50283. Ideal for ok/cancel or yes/no choices. The return key can also be used
  50284. to trigger the first button, and the escape key for the second button.
  50285. If the callback parameter is null, the box is shown modally, and the method will
  50286. block until the user has clicked the button (or pressed the escape or return keys).
  50287. If the callback parameter is non-null, the box will be displayed and placed into a
  50288. modal state, but this method will return immediately, and the callback will be invoked
  50289. later when the user dismisses the box.
  50290. @param iconType the type of icon to show
  50291. @param title the headline to show at the top of the box
  50292. @param message a longer, more descriptive message to show underneath the title
  50293. @param associatedComponent if this is non-null, it specifies the component that the
  50294. alert window should be associated with. Depending on the look
  50295. and feel, this might be used for positioning of the alert window.
  50296. @param callback if this is non-null, the menu will be launched asynchronously,
  50297. returning immediately, and the callback will receive a call to its
  50298. modalStateFinished() when the box is dismissed, with its parameter
  50299. being 1 if the ok button was pressed, or 0 for cancel, The callback object
  50300. will be owned and deleted by the system, so make sure that it works
  50301. safely and doesn't keep any references to objects that might be deleted
  50302. before it gets called.
  50303. @returns true if button 1 was clicked, false if it was button 2. If the callback parameter
  50304. is not null, the method always returns false, and the user's choice is delivered
  50305. later by the callback.
  50306. */
  50307. static bool JUCE_CALLTYPE showOkCancelBox (AlertWindow::AlertIconType iconType,
  50308. const String& title,
  50309. const String& message,
  50310. #if JUCE_MODAL_LOOPS_PERMITTED
  50311. Component* associatedComponent = nullptr,
  50312. ModalComponentManager::Callback* callback = nullptr);
  50313. #else
  50314. Component* associatedComponent,
  50315. ModalComponentManager::Callback* callback);
  50316. #endif
  50317. /** Shows a dialog box with three buttons.
  50318. Ideal for yes/no/cancel boxes.
  50319. The escape key can be used to trigger the third button.
  50320. If the callback parameter is null, the box is shown modally, and the method will
  50321. block until the user has clicked the button (or pressed the escape or return keys).
  50322. If the callback parameter is non-null, the box will be displayed and placed into a
  50323. modal state, but this method will return immediately, and the callback will be invoked
  50324. later when the user dismisses the box.
  50325. @param iconType the type of icon to show
  50326. @param title the headline to show at the top of the box
  50327. @param message a longer, more descriptive message to show underneath the title
  50328. @param associatedComponent if this is non-null, it specifies the component that the
  50329. alert window should be associated with. Depending on the look
  50330. and feel, this might be used for positioning of the alert window.
  50331. @param callback if this is non-null, the menu will be launched asynchronously,
  50332. returning immediately, and the callback will receive a call to its
  50333. modalStateFinished() when the box is dismissed, with its parameter
  50334. being 1 if the "yes" button was pressed, 2 for the "no" button, or 0
  50335. if it was cancelled, The callback object will be owned and deleted by the
  50336. system, so make sure that it works safely and doesn't keep any references
  50337. to objects that might be deleted before it gets called.
  50338. @returns If the callback parameter has been set, this returns 0. Otherwise, it returns one
  50339. of the following values:
  50340. - 0 if 'cancel' was pressed
  50341. - 1 if 'yes' was pressed
  50342. - 2 if 'no' was pressed
  50343. */
  50344. static int JUCE_CALLTYPE showYesNoCancelBox (AlertWindow::AlertIconType iconType,
  50345. const String& title,
  50346. const String& message,
  50347. #if JUCE_MODAL_LOOPS_PERMITTED
  50348. Component* associatedComponent = nullptr,
  50349. ModalComponentManager::Callback* callback = nullptr);
  50350. #else
  50351. Component* associatedComponent,
  50352. ModalComponentManager::Callback* callback);
  50353. #endif
  50354. };
  50355. #endif // __JUCE_NATIVEMESSAGEBOX_JUCEHEADER__
  50356. /*** End of inlined file: juce_NativeMessageBox.h ***/
  50357. #endif
  50358. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  50359. #endif
  50360. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  50361. /*** Start of inlined file: juce_SplashScreen.h ***/
  50362. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  50363. #define __JUCE_SPLASHSCREEN_JUCEHEADER__
  50364. /** A component for showing a splash screen while your app starts up.
  50365. This will automatically position itself, and delete itself when the app has
  50366. finished initialising (it uses the JUCEApplication::isInitialising() to detect
  50367. this).
  50368. To use it, just create one of these in your JUCEApplication::initialise() method,
  50369. call its show() method and let the object delete itself later.
  50370. E.g. @code
  50371. void MyApp::initialise (const String& commandLine)
  50372. {
  50373. SplashScreen* splash = new SplashScreen();
  50374. splash->show ("welcome to my app",
  50375. ImageCache::getFromFile (File ("/foobar/splash.jpg")),
  50376. 4000, false);
  50377. .. no need to delete the splash screen - it'll do that itself.
  50378. }
  50379. @endcode
  50380. */
  50381. class JUCE_API SplashScreen : public Component,
  50382. public Timer,
  50383. private DeletedAtShutdown
  50384. {
  50385. public:
  50386. /** Creates a SplashScreen object.
  50387. After creating one of these (or your subclass of it), call one of the show()
  50388. methods to display it.
  50389. */
  50390. SplashScreen();
  50391. /** Destructor. */
  50392. ~SplashScreen();
  50393. /** Creates a SplashScreen object that will display an image.
  50394. As soon as this is called, the SplashScreen will be displayed in the centre of the
  50395. screen. This method will also dispatch any pending messages to make sure that when
  50396. it returns, the splash screen has been completely drawn, and your initialisation
  50397. code can carry on.
  50398. @param title the name to give the component
  50399. @param backgroundImage an image to draw on the component. The component's size
  50400. will be set to the size of this image, and if the image is
  50401. semi-transparent, the component will be made semi-transparent
  50402. too. This image will be deleted (or released from the ImageCache
  50403. if that's how it was created) by the splash screen object when
  50404. it is itself deleted.
  50405. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  50406. should stay visible for. If the initialisation takes longer than
  50407. this time, the splash screen will wait for it to finish before
  50408. disappearing, but if initialisation is very quick, this lets
  50409. you make sure that people get a good look at your splash.
  50410. @param useDropShadow if true, the window will have a drop shadow
  50411. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  50412. the mouse (anywhere)
  50413. */
  50414. void show (const String& title,
  50415. const Image& backgroundImage,
  50416. int minimumTimeToDisplayFor,
  50417. bool useDropShadow,
  50418. bool removeOnMouseClick = true);
  50419. /** Creates a SplashScreen object with a specified size.
  50420. For a custom splash screen, you can use this method to display it at a certain size
  50421. and then override the paint() method yourself to do whatever's necessary.
  50422. As soon as this is called, the SplashScreen will be displayed in the centre of the
  50423. screen. This method will also dispatch any pending messages to make sure that when
  50424. it returns, the splash screen has been completely drawn, and your initialisation
  50425. code can carry on.
  50426. @param title the name to give the component
  50427. @param width the width to use
  50428. @param height the height to use
  50429. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  50430. should stay visible for. If the initialisation takes longer than
  50431. this time, the splash screen will wait for it to finish before
  50432. disappearing, but if initialisation is very quick, this lets
  50433. you make sure that people get a good look at your splash.
  50434. @param useDropShadow if true, the window will have a drop shadow
  50435. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  50436. the mouse (anywhere)
  50437. */
  50438. void show (const String& title,
  50439. int width,
  50440. int height,
  50441. int minimumTimeToDisplayFor,
  50442. bool useDropShadow,
  50443. bool removeOnMouseClick = true);
  50444. /** @internal */
  50445. void paint (Graphics& g);
  50446. /** @internal */
  50447. void timerCallback();
  50448. private:
  50449. Image backgroundImage;
  50450. Time earliestTimeToDelete;
  50451. int originalClickCounter;
  50452. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SplashScreen);
  50453. };
  50454. #endif // __JUCE_SPLASHSCREEN_JUCEHEADER__
  50455. /*** End of inlined file: juce_SplashScreen.h ***/
  50456. #endif
  50457. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  50458. /*** Start of inlined file: juce_ThreadWithProgressWindow.h ***/
  50459. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  50460. #define __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  50461. /**
  50462. A thread that automatically pops up a modal dialog box with a progress bar
  50463. and cancel button while it's busy running.
  50464. These are handy for performing some sort of task while giving the user feedback
  50465. about how long there is to go, etc.
  50466. E.g. @code
  50467. class MyTask : public ThreadWithProgressWindow
  50468. {
  50469. public:
  50470. MyTask() : ThreadWithProgressWindow ("busy...", true, true)
  50471. {
  50472. }
  50473. ~MyTask()
  50474. {
  50475. }
  50476. void run()
  50477. {
  50478. for (int i = 0; i < thingsToDo; ++i)
  50479. {
  50480. // must check this as often as possible, because this is
  50481. // how we know if the user's pressed 'cancel'
  50482. if (threadShouldExit())
  50483. break;
  50484. // this will update the progress bar on the dialog box
  50485. setProgress (i / (double) thingsToDo);
  50486. // ... do the business here...
  50487. }
  50488. }
  50489. };
  50490. void doTheTask()
  50491. {
  50492. MyTask m;
  50493. if (m.runThread())
  50494. {
  50495. // thread finished normally..
  50496. }
  50497. else
  50498. {
  50499. // user pressed the cancel button..
  50500. }
  50501. }
  50502. @endcode
  50503. @see Thread, AlertWindow
  50504. */
  50505. class JUCE_API ThreadWithProgressWindow : public Thread,
  50506. private Timer
  50507. {
  50508. public:
  50509. /** Creates the thread.
  50510. Initially, the dialog box won't be visible, it'll only appear when the
  50511. runThread() method is called.
  50512. @param windowTitle the title to go at the top of the dialog box
  50513. @param hasProgressBar whether the dialog box should have a progress bar (see
  50514. setProgress() )
  50515. @param hasCancelButton whether the dialog box should have a cancel button
  50516. @param timeOutMsWhenCancelling when 'cancel' is pressed, this is how long to wait for
  50517. the thread to stop before killing it forcibly (see
  50518. Thread::stopThread() )
  50519. @param cancelButtonText the text that should be shown in the cancel button
  50520. (if it has one)
  50521. */
  50522. ThreadWithProgressWindow (const String& windowTitle,
  50523. bool hasProgressBar,
  50524. bool hasCancelButton,
  50525. int timeOutMsWhenCancelling = 10000,
  50526. const String& cancelButtonText = "Cancel");
  50527. /** Destructor. */
  50528. ~ThreadWithProgressWindow();
  50529. /** Starts the thread and waits for it to finish.
  50530. This will start the thread, make the dialog box appear, and wait until either
  50531. the thread finishes normally, or until the cancel button is pressed.
  50532. Before returning, the dialog box will be hidden.
  50533. @param threadPriority the priority to use when starting the thread - see
  50534. Thread::startThread() for values
  50535. @returns true if the thread finished normally; false if the user pressed cancel
  50536. */
  50537. bool runThread (int threadPriority = 5);
  50538. /** The thread should call this periodically to update the position of the progress bar.
  50539. @param newProgress the progress, from 0.0 to 1.0
  50540. @see setStatusMessage
  50541. */
  50542. void setProgress (double newProgress);
  50543. /** The thread can call this to change the message that's displayed in the dialog box.
  50544. */
  50545. void setStatusMessage (const String& newStatusMessage);
  50546. /** Returns the AlertWindow that is being used.
  50547. */
  50548. AlertWindow* getAlertWindow() const noexcept { return alertWindow; }
  50549. private:
  50550. void timerCallback();
  50551. double progress;
  50552. ScopedPointer <AlertWindow> alertWindow;
  50553. String message;
  50554. CriticalSection messageLock;
  50555. const int timeOutMsWhenCancelling;
  50556. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadWithProgressWindow);
  50557. };
  50558. #endif // __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  50559. /*** End of inlined file: juce_ThreadWithProgressWindow.h ***/
  50560. #endif
  50561. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  50562. #endif
  50563. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  50564. #endif
  50565. #ifndef __JUCE_COLOUR_JUCEHEADER__
  50566. #endif
  50567. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  50568. #endif
  50569. #ifndef __JUCE_COLOURS_JUCEHEADER__
  50570. #endif
  50571. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  50572. #endif
  50573. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  50574. /*** Start of inlined file: juce_EdgeTable.h ***/
  50575. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  50576. #define __JUCE_EDGETABLE_JUCEHEADER__
  50577. class Path;
  50578. class Image;
  50579. /**
  50580. A table of horizontal scan-line segments - used for rasterising Paths.
  50581. @see Path, Graphics
  50582. */
  50583. class JUCE_API EdgeTable
  50584. {
  50585. public:
  50586. /** Creates an edge table containing a path.
  50587. A table is created with a fixed vertical range, and only sections of the path
  50588. which lie within this range will be added to the table.
  50589. @param clipLimits only the region of the path that lies within this area will be added
  50590. @param pathToAdd the path to add to the table
  50591. @param transform a transform to apply to the path being added
  50592. */
  50593. EdgeTable (const Rectangle<int>& clipLimits,
  50594. const Path& pathToAdd,
  50595. const AffineTransform& transform);
  50596. /** Creates an edge table containing a rectangle. */
  50597. EdgeTable (const Rectangle<int>& rectangleToAdd);
  50598. /** Creates an edge table containing a rectangle list. */
  50599. EdgeTable (const RectangleList& rectanglesToAdd);
  50600. /** Creates an edge table containing a rectangle. */
  50601. EdgeTable (const Rectangle<float>& rectangleToAdd);
  50602. /** Creates a copy of another edge table. */
  50603. EdgeTable (const EdgeTable& other);
  50604. /** Copies from another edge table. */
  50605. EdgeTable& operator= (const EdgeTable& other);
  50606. /** Destructor. */
  50607. ~EdgeTable();
  50608. void clipToRectangle (const Rectangle<int>& r);
  50609. void excludeRectangle (const Rectangle<int>& r);
  50610. void clipToEdgeTable (const EdgeTable& other);
  50611. void clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels);
  50612. bool isEmpty() noexcept;
  50613. const Rectangle<int>& getMaximumBounds() const noexcept { return bounds; }
  50614. void translate (float dx, int dy) noexcept;
  50615. /** Reduces the amount of space the table has allocated.
  50616. This will shrink the table down to use as little memory as possible - useful for
  50617. read-only tables that get stored and re-used for rendering.
  50618. */
  50619. void optimiseTable();
  50620. /** Iterates the lines in the table, for rendering.
  50621. This function will iterate each line in the table, and call a user-defined class
  50622. to render each pixel or continuous line of pixels that the table contains.
  50623. @param iterationCallback this templated class must contain the following methods:
  50624. @code
  50625. inline void setEdgeTableYPos (int y);
  50626. inline void handleEdgeTablePixel (int x, int alphaLevel) const;
  50627. inline void handleEdgeTablePixelFull (int x) const;
  50628. inline void handleEdgeTableLine (int x, int width, int alphaLevel) const;
  50629. inline void handleEdgeTableLineFull (int x, int width) const;
  50630. @endcode
  50631. (these don't necessarily have to be 'const', but it might help it go faster)
  50632. */
  50633. template <class EdgeTableIterationCallback>
  50634. void iterate (EdgeTableIterationCallback& iterationCallback) const noexcept
  50635. {
  50636. const int* lineStart = table;
  50637. for (int y = 0; y < bounds.getHeight(); ++y)
  50638. {
  50639. const int* line = lineStart;
  50640. lineStart += lineStrideElements;
  50641. int numPoints = line[0];
  50642. if (--numPoints > 0)
  50643. {
  50644. int x = *++line;
  50645. jassert ((x >> 8) >= bounds.getX() && (x >> 8) < bounds.getRight());
  50646. int levelAccumulator = 0;
  50647. iterationCallback.setEdgeTableYPos (bounds.getY() + y);
  50648. while (--numPoints >= 0)
  50649. {
  50650. const int level = *++line;
  50651. jassert (isPositiveAndBelow (level, (int) 256));
  50652. const int endX = *++line;
  50653. jassert (endX >= x);
  50654. const int endOfRun = (endX >> 8);
  50655. if (endOfRun == (x >> 8))
  50656. {
  50657. // small segment within the same pixel, so just save it for the next
  50658. // time round..
  50659. levelAccumulator += (endX - x) * level;
  50660. }
  50661. else
  50662. {
  50663. // plot the fist pixel of this segment, including any accumulated
  50664. // levels from smaller segments that haven't been drawn yet
  50665. levelAccumulator += (0x100 - (x & 0xff)) * level;
  50666. levelAccumulator >>= 8;
  50667. x >>= 8;
  50668. if (levelAccumulator > 0)
  50669. {
  50670. if (levelAccumulator >= 255)
  50671. iterationCallback.handleEdgeTablePixelFull (x);
  50672. else
  50673. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  50674. }
  50675. // if there's a run of similar pixels, do it all in one go..
  50676. if (level > 0)
  50677. {
  50678. jassert (endOfRun <= bounds.getRight());
  50679. const int numPix = endOfRun - ++x;
  50680. if (numPix > 0)
  50681. iterationCallback.handleEdgeTableLine (x, numPix, level);
  50682. }
  50683. // save the bit at the end to be drawn next time round the loop.
  50684. levelAccumulator = (endX & 0xff) * level;
  50685. }
  50686. x = endX;
  50687. }
  50688. levelAccumulator >>= 8;
  50689. if (levelAccumulator > 0)
  50690. {
  50691. x >>= 8;
  50692. jassert (x >= bounds.getX() && x < bounds.getRight());
  50693. if (levelAccumulator >= 255)
  50694. iterationCallback.handleEdgeTablePixelFull (x);
  50695. else
  50696. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  50697. }
  50698. }
  50699. }
  50700. }
  50701. private:
  50702. // table line format: number of points; point0 x, point0 levelDelta, point1 x, point1 levelDelta, etc
  50703. HeapBlock<int> table;
  50704. Rectangle<int> bounds;
  50705. int maxEdgesPerLine, lineStrideElements;
  50706. bool needToCheckEmptinesss;
  50707. void addEdgePoint (int x, int y, int winding);
  50708. void remapTableForNumEdges (int newNumEdgesPerLine);
  50709. void intersectWithEdgeTableLine (int y, const int* otherLine);
  50710. void clipEdgeTableLineToRange (int* line, int x1, int x2) noexcept;
  50711. void sanitiseLevels (bool useNonZeroWinding) noexcept;
  50712. static void copyEdgeTableData (int* dest, int destLineStride, const int* src, int srcLineStride, int numLines) noexcept;
  50713. JUCE_LEAK_DETECTOR (EdgeTable);
  50714. };
  50715. #endif // __JUCE_EDGETABLE_JUCEHEADER__
  50716. /*** End of inlined file: juce_EdgeTable.h ***/
  50717. #endif
  50718. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  50719. /*** Start of inlined file: juce_FillType.h ***/
  50720. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  50721. #define __JUCE_FILLTYPE_JUCEHEADER__
  50722. /**
  50723. Represents a colour or fill pattern to use for rendering paths.
  50724. This is used by the Graphics and DrawablePath classes as a way to encapsulate
  50725. a brush type. It can either be a solid colour, a gradient, or a tiled image.
  50726. @see Graphics::setFillType, DrawablePath::setFill
  50727. */
  50728. class JUCE_API FillType
  50729. {
  50730. public:
  50731. /** Creates a default fill type, of solid black. */
  50732. FillType() noexcept;
  50733. /** Creates a fill type of a solid colour.
  50734. @see setColour
  50735. */
  50736. FillType (const Colour& colour) noexcept;
  50737. /** Creates a gradient fill type.
  50738. @see setGradient
  50739. */
  50740. FillType (const ColourGradient& gradient);
  50741. /** Creates a tiled image fill type. The transform allows you to set the scaling, offset
  50742. and rotation of the pattern.
  50743. @see setTiledImage
  50744. */
  50745. FillType (const Image& image, const AffineTransform& transform) noexcept;
  50746. /** Creates a copy of another FillType. */
  50747. FillType (const FillType& other);
  50748. /** Makes a copy of another FillType. */
  50749. FillType& operator= (const FillType& other);
  50750. /** Destructor. */
  50751. ~FillType() noexcept;
  50752. /** Returns true if this is a solid colour fill, and not a gradient or image. */
  50753. bool isColour() const noexcept { return gradient == nullptr && image.isNull(); }
  50754. /** Returns true if this is a gradient fill. */
  50755. bool isGradient() const noexcept { return gradient != nullptr; }
  50756. /** Returns true if this is a tiled image pattern fill. */
  50757. bool isTiledImage() const noexcept { return image.isValid(); }
  50758. /** Turns this object into a solid colour fill.
  50759. If the object was an image or gradient, those fields will no longer be valid. */
  50760. void setColour (const Colour& newColour) noexcept;
  50761. /** Turns this object into a gradient fill. */
  50762. void setGradient (const ColourGradient& newGradient);
  50763. /** Turns this object into a tiled image fill type. The transform allows you to set
  50764. the scaling, offset and rotation of the pattern.
  50765. */
  50766. void setTiledImage (const Image& image, const AffineTransform& transform) noexcept;
  50767. /** Changes the opacity that should be used.
  50768. If the fill is a solid colour, this just changes the opacity of that colour. For
  50769. gradients and image tiles, it changes the opacity that will be used for them.
  50770. */
  50771. void setOpacity (float newOpacity) noexcept;
  50772. /** Returns the current opacity to be applied to the colour, gradient, or image.
  50773. @see setOpacity
  50774. */
  50775. float getOpacity() const noexcept { return colour.getFloatAlpha(); }
  50776. /** Returns true if this fill type is completely transparent. */
  50777. bool isInvisible() const noexcept;
  50778. /** The solid colour being used.
  50779. If the fill type is not a solid colour, the alpha channel of this colour indicates
  50780. the opacity that should be used for the fill, and the RGB channels are ignored.
  50781. */
  50782. Colour colour;
  50783. /** Returns the gradient that should be used for filling.
  50784. This will be zero if the object is some other type of fill.
  50785. If a gradient is active, the overall opacity with which it should be applied
  50786. is indicated by the alpha channel of the colour variable.
  50787. */
  50788. ScopedPointer <ColourGradient> gradient;
  50789. /** The image that should be used for tiling.
  50790. If an image fill is active, the overall opacity with which it should be applied
  50791. is indicated by the alpha channel of the colour variable.
  50792. */
  50793. Image image;
  50794. /** The transform that should be applied to the image or gradient that's being drawn. */
  50795. AffineTransform transform;
  50796. bool operator== (const FillType& other) const;
  50797. bool operator!= (const FillType& other) const;
  50798. private:
  50799. JUCE_LEAK_DETECTOR (FillType);
  50800. };
  50801. #endif // __JUCE_FILLTYPE_JUCEHEADER__
  50802. /*** End of inlined file: juce_FillType.h ***/
  50803. #endif
  50804. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  50805. #endif
  50806. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  50807. #endif
  50808. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  50809. /*** Start of inlined file: juce_LowLevelGraphicsContext.h ***/
  50810. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  50811. #define __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  50812. /**
  50813. Interface class for graphics context objects, used internally by the Graphics class.
  50814. Users are not supposed to create instances of this class directly - do your drawing
  50815. via the Graphics object instead.
  50816. It's a base class for different types of graphics context, that may perform software-based
  50817. or OS-accelerated rendering.
  50818. E.g. the LowLevelGraphicsSoftwareRenderer renders onto an image in memory, but other
  50819. subclasses could render directly to a windows HDC, a Quartz context, or an OpenGL
  50820. context.
  50821. */
  50822. class JUCE_API LowLevelGraphicsContext
  50823. {
  50824. protected:
  50825. LowLevelGraphicsContext();
  50826. public:
  50827. virtual ~LowLevelGraphicsContext();
  50828. /** Returns true if this device is vector-based, e.g. a printer. */
  50829. virtual bool isVectorDevice() const = 0;
  50830. /** Moves the origin to a new position.
  50831. The co-ords are relative to the current origin, and indicate the new position
  50832. of (0, 0).
  50833. */
  50834. virtual void setOrigin (int x, int y) = 0;
  50835. virtual void addTransform (const AffineTransform& transform) = 0;
  50836. virtual float getScaleFactor() = 0;
  50837. virtual bool clipToRectangle (const Rectangle<int>& r) = 0;
  50838. virtual bool clipToRectangleList (const RectangleList& clipRegion) = 0;
  50839. virtual void excludeClipRectangle (const Rectangle<int>& r) = 0;
  50840. virtual void clipToPath (const Path& path, const AffineTransform& transform) = 0;
  50841. virtual void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform) = 0;
  50842. virtual bool clipRegionIntersects (const Rectangle<int>& r) = 0;
  50843. virtual const Rectangle<int> getClipBounds() const = 0;
  50844. virtual bool isClipEmpty() const = 0;
  50845. virtual void saveState() = 0;
  50846. virtual void restoreState() = 0;
  50847. virtual void beginTransparencyLayer (float opacity) = 0;
  50848. virtual void endTransparencyLayer() = 0;
  50849. virtual void setFill (const FillType& fillType) = 0;
  50850. virtual void setOpacity (float newOpacity) = 0;
  50851. virtual void setInterpolationQuality (Graphics::ResamplingQuality quality) = 0;
  50852. virtual void fillRect (const Rectangle<int>& r, bool replaceExistingContents) = 0;
  50853. virtual void fillPath (const Path& path, const AffineTransform& transform) = 0;
  50854. virtual void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles) = 0;
  50855. virtual void drawLine (const Line <float>& line) = 0;
  50856. virtual void drawVerticalLine (int x, float top, float bottom) = 0;
  50857. virtual void drawHorizontalLine (int y, float left, float right) = 0;
  50858. virtual void setFont (const Font& newFont) = 0;
  50859. virtual Font getFont() = 0;
  50860. virtual void drawGlyph (int glyphNumber, const AffineTransform& transform) = 0;
  50861. };
  50862. #endif // __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  50863. /*** End of inlined file: juce_LowLevelGraphicsContext.h ***/
  50864. #endif
  50865. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  50866. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  50867. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  50868. #define __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  50869. /**
  50870. An implementation of LowLevelGraphicsContext that turns the drawing operations
  50871. into a PostScript document.
  50872. */
  50873. class JUCE_API LowLevelGraphicsPostScriptRenderer : public LowLevelGraphicsContext
  50874. {
  50875. public:
  50876. LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  50877. const String& documentTitle,
  50878. int totalWidth,
  50879. int totalHeight);
  50880. ~LowLevelGraphicsPostScriptRenderer();
  50881. bool isVectorDevice() const;
  50882. void setOrigin (int x, int y);
  50883. void addTransform (const AffineTransform& transform);
  50884. float getScaleFactor();
  50885. bool clipToRectangle (const Rectangle<int>& r);
  50886. bool clipToRectangleList (const RectangleList& clipRegion);
  50887. void excludeClipRectangle (const Rectangle<int>& r);
  50888. void clipToPath (const Path& path, const AffineTransform& transform);
  50889. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform);
  50890. void saveState();
  50891. void restoreState();
  50892. void beginTransparencyLayer (float opacity);
  50893. void endTransparencyLayer();
  50894. bool clipRegionIntersects (const Rectangle<int>& r);
  50895. const Rectangle<int> getClipBounds() const;
  50896. bool isClipEmpty() const;
  50897. void setFill (const FillType& fillType);
  50898. void setOpacity (float opacity);
  50899. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  50900. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  50901. void fillPath (const Path& path, const AffineTransform& transform);
  50902. void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles);
  50903. void drawLine (const Line <float>& line);
  50904. void drawVerticalLine (int x, float top, float bottom);
  50905. void drawHorizontalLine (int x, float top, float bottom);
  50906. Font getFont();
  50907. void setFont (const Font& newFont);
  50908. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  50909. protected:
  50910. OutputStream& out;
  50911. int totalWidth, totalHeight;
  50912. bool needToClip;
  50913. Colour lastColour;
  50914. struct SavedState
  50915. {
  50916. SavedState();
  50917. ~SavedState();
  50918. RectangleList clip;
  50919. int xOffset, yOffset;
  50920. FillType fillType;
  50921. Font font;
  50922. private:
  50923. SavedState& operator= (const SavedState&);
  50924. };
  50925. OwnedArray <SavedState> stateStack;
  50926. void writeClip();
  50927. void writeColour (const Colour& colour);
  50928. void writePath (const Path& path) const;
  50929. void writeXY (float x, float y) const;
  50930. void writeTransform (const AffineTransform& trans) const;
  50931. void writeImage (const Image& im, int sx, int sy, int maxW, int maxH) const;
  50932. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LowLevelGraphicsPostScriptRenderer);
  50933. };
  50934. #endif // __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  50935. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  50936. #endif
  50937. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  50938. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  50939. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  50940. #define __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  50941. /**
  50942. A lowest-common-denominator implementation of LowLevelGraphicsContext that does all
  50943. its rendering in memory.
  50944. User code is not supposed to create instances of this class directly - do all your
  50945. rendering via the Graphics class instead.
  50946. */
  50947. class JUCE_API LowLevelGraphicsSoftwareRenderer : public LowLevelGraphicsContext
  50948. {
  50949. public:
  50950. LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOn);
  50951. LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOn, int xOffset, int yOffset, const RectangleList& initialClip);
  50952. ~LowLevelGraphicsSoftwareRenderer();
  50953. bool isVectorDevice() const;
  50954. void setOrigin (int x, int y);
  50955. void addTransform (const AffineTransform& transform);
  50956. float getScaleFactor();
  50957. bool clipToRectangle (const Rectangle<int>& r);
  50958. bool clipToRectangleList (const RectangleList& clipRegion);
  50959. void excludeClipRectangle (const Rectangle<int>& r);
  50960. void clipToPath (const Path& path, const AffineTransform& transform);
  50961. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform);
  50962. bool clipRegionIntersects (const Rectangle<int>& r);
  50963. const Rectangle<int> getClipBounds() const;
  50964. bool isClipEmpty() const;
  50965. void saveState();
  50966. void restoreState();
  50967. void beginTransparencyLayer (float opacity);
  50968. void endTransparencyLayer();
  50969. void setFill (const FillType& fillType);
  50970. void setOpacity (float opacity);
  50971. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  50972. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  50973. void fillPath (const Path& path, const AffineTransform& transform);
  50974. void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles);
  50975. void drawLine (const Line <float>& line);
  50976. void drawVerticalLine (int x, float top, float bottom);
  50977. void drawHorizontalLine (int x, float top, float bottom);
  50978. void setFont (const Font& newFont);
  50979. Font getFont();
  50980. void drawGlyph (int glyphNumber, float x, float y);
  50981. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  50982. protected:
  50983. Image image;
  50984. class GlyphCache;
  50985. class CachedGlyph;
  50986. class SavedState;
  50987. friend class ScopedPointer <SavedState>;
  50988. friend class OwnedArray <SavedState>;
  50989. friend class OwnedArray <CachedGlyph>;
  50990. ScopedPointer <SavedState> currentState;
  50991. OwnedArray <SavedState> stateStack;
  50992. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LowLevelGraphicsSoftwareRenderer);
  50993. };
  50994. #endif // __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  50995. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  50996. #endif
  50997. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  50998. #endif
  50999. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  51000. #endif
  51001. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  51002. /*** Start of inlined file: juce_DrawableComposite.h ***/
  51003. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  51004. #define __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  51005. /**
  51006. A drawable object which acts as a container for a set of other Drawables.
  51007. @see Drawable
  51008. */
  51009. class JUCE_API DrawableComposite : public Drawable
  51010. {
  51011. public:
  51012. /** Creates a composite Drawable. */
  51013. DrawableComposite();
  51014. /** Creates a copy of a DrawableComposite. */
  51015. DrawableComposite (const DrawableComposite& other);
  51016. /** Destructor. */
  51017. ~DrawableComposite();
  51018. /** Sets the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
  51019. @see setContentArea
  51020. */
  51021. void setBoundingBox (const RelativeParallelogram& newBoundingBox);
  51022. /** Returns the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
  51023. @see setBoundingBox
  51024. */
  51025. const RelativeParallelogram& getBoundingBox() const noexcept { return bounds; }
  51026. /** Changes the bounding box transform to match the content area, so that any sub-items will
  51027. be drawn at their untransformed positions.
  51028. */
  51029. void resetBoundingBoxToContentArea();
  51030. /** Returns the main content rectangle.
  51031. The content area is actually defined by the markers named "left", "right", "top" and
  51032. "bottom", but this method is a shortcut that returns them all at once.
  51033. @see contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
  51034. */
  51035. RelativeRectangle getContentArea() const;
  51036. /** Changes the main content area.
  51037. The content area is actually defined by the markers named "left", "right", "top" and
  51038. "bottom", but this method is a shortcut that sets them all at once.
  51039. @see setBoundingBox, contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
  51040. */
  51041. void setContentArea (const RelativeRectangle& newArea);
  51042. /** Resets the content area and the bounding transform to fit around the area occupied
  51043. by the child components (ignoring any markers).
  51044. */
  51045. void resetContentAreaAndBoundingBoxToFitChildren();
  51046. /** The name of the marker that defines the left edge of the content area. */
  51047. static const char* const contentLeftMarkerName;
  51048. /** The name of the marker that defines the right edge of the content area. */
  51049. static const char* const contentRightMarkerName;
  51050. /** The name of the marker that defines the top edge of the content area. */
  51051. static const char* const contentTopMarkerName;
  51052. /** The name of the marker that defines the bottom edge of the content area. */
  51053. static const char* const contentBottomMarkerName;
  51054. /** @internal */
  51055. Drawable* createCopy() const;
  51056. /** @internal */
  51057. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  51058. /** @internal */
  51059. ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  51060. /** @internal */
  51061. static const Identifier valueTreeType;
  51062. /** @internal */
  51063. Rectangle<float> getDrawableBounds() const;
  51064. /** @internal */
  51065. void childBoundsChanged (Component*);
  51066. /** @internal */
  51067. void childrenChanged();
  51068. /** @internal */
  51069. void parentHierarchyChanged();
  51070. /** @internal */
  51071. MarkerList* getMarkers (bool xAxis);
  51072. /** Internally-used class for wrapping a DrawableComposite's state into a ValueTree. */
  51073. class ValueTreeWrapper : public Drawable::ValueTreeWrapperBase
  51074. {
  51075. public:
  51076. ValueTreeWrapper (const ValueTree& state);
  51077. ValueTree getChildList() const;
  51078. ValueTree getChildListCreating (UndoManager* undoManager);
  51079. RelativeParallelogram getBoundingBox() const;
  51080. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  51081. void resetBoundingBoxToContentArea (UndoManager* undoManager);
  51082. RelativeRectangle getContentArea() const;
  51083. void setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager);
  51084. MarkerList::ValueTreeWrapper getMarkerList (bool xAxis) const;
  51085. MarkerList::ValueTreeWrapper getMarkerListCreating (bool xAxis, UndoManager* undoManager);
  51086. static const Identifier topLeft, topRight, bottomLeft;
  51087. private:
  51088. static const Identifier childGroupTag, markerGroupTagX, markerGroupTagY;
  51089. };
  51090. private:
  51091. RelativeParallelogram bounds;
  51092. MarkerList markersX, markersY;
  51093. bool updateBoundsReentrant;
  51094. friend class Drawable::Positioner<DrawableComposite>;
  51095. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  51096. void recalculateCoordinates (Expression::Scope*);
  51097. void updateBoundsToFitChildren();
  51098. DrawableComposite& operator= (const DrawableComposite&);
  51099. JUCE_LEAK_DETECTOR (DrawableComposite);
  51100. };
  51101. #endif // __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  51102. /*** End of inlined file: juce_DrawableComposite.h ***/
  51103. #endif
  51104. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  51105. /*** Start of inlined file: juce_DrawableImage.h ***/
  51106. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  51107. #define __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  51108. /**
  51109. A drawable object which is a bitmap image.
  51110. @see Drawable
  51111. */
  51112. class JUCE_API DrawableImage : public Drawable
  51113. {
  51114. public:
  51115. DrawableImage();
  51116. DrawableImage (const DrawableImage& other);
  51117. /** Destructor. */
  51118. ~DrawableImage();
  51119. /** Sets the image that this drawable will render. */
  51120. void setImage (const Image& imageToUse);
  51121. /** Returns the current image. */
  51122. const Image& getImage() const noexcept { return image; }
  51123. /** Sets the opacity to use when drawing the image. */
  51124. void setOpacity (float newOpacity);
  51125. /** Returns the image's opacity. */
  51126. float getOpacity() const noexcept { return opacity; }
  51127. /** Sets a colour to draw over the image's alpha channel.
  51128. By default this is transparent so isn't drawn, but if you set a non-transparent
  51129. colour here, then it will be overlaid on the image, using the image's alpha
  51130. channel as a mask.
  51131. This is handy for doing things like darkening or lightening an image by overlaying
  51132. it with semi-transparent black or white.
  51133. */
  51134. void setOverlayColour (const Colour& newOverlayColour);
  51135. /** Returns the overlay colour. */
  51136. const Colour& getOverlayColour() const noexcept { return overlayColour; }
  51137. /** Sets the bounding box within which the image should be displayed. */
  51138. void setBoundingBox (const RelativeParallelogram& newBounds);
  51139. /** Returns the position to which the image's top-left corner should be remapped in the target
  51140. coordinate space when rendering this object.
  51141. @see setTransform
  51142. */
  51143. const RelativeParallelogram& getBoundingBox() const noexcept { return bounds; }
  51144. /** @internal */
  51145. void paint (Graphics& g);
  51146. /** @internal */
  51147. bool hitTest (int x, int y);
  51148. /** @internal */
  51149. Drawable* createCopy() const;
  51150. /** @internal */
  51151. Rectangle<float> getDrawableBounds() const;
  51152. /** @internal */
  51153. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  51154. /** @internal */
  51155. ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  51156. /** @internal */
  51157. static const Identifier valueTreeType;
  51158. /** Internally-used class for wrapping a DrawableImage's state into a ValueTree. */
  51159. class ValueTreeWrapper : public Drawable::ValueTreeWrapperBase
  51160. {
  51161. public:
  51162. ValueTreeWrapper (const ValueTree& state);
  51163. var getImageIdentifier() const;
  51164. void setImageIdentifier (const var& newIdentifier, UndoManager* undoManager);
  51165. Value getImageIdentifierValue (UndoManager* undoManager);
  51166. float getOpacity() const;
  51167. void setOpacity (float newOpacity, UndoManager* undoManager);
  51168. Value getOpacityValue (UndoManager* undoManager);
  51169. const Colour getOverlayColour() const;
  51170. void setOverlayColour (const Colour& newColour, UndoManager* undoManager);
  51171. Value getOverlayColourValue (UndoManager* undoManager);
  51172. RelativeParallelogram getBoundingBox() const;
  51173. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  51174. static const Identifier opacity, overlay, image, topLeft, topRight, bottomLeft;
  51175. };
  51176. private:
  51177. Image image;
  51178. float opacity;
  51179. Colour overlayColour;
  51180. RelativeParallelogram bounds;
  51181. friend class Drawable::Positioner<DrawableImage>;
  51182. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  51183. void recalculateCoordinates (Expression::Scope*);
  51184. DrawableImage& operator= (const DrawableImage&);
  51185. JUCE_LEAK_DETECTOR (DrawableImage);
  51186. };
  51187. #endif // __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  51188. /*** End of inlined file: juce_DrawableImage.h ***/
  51189. #endif
  51190. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  51191. /*** Start of inlined file: juce_DrawablePath.h ***/
  51192. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  51193. #define __JUCE_DRAWABLEPATH_JUCEHEADER__
  51194. /*** Start of inlined file: juce_DrawableShape.h ***/
  51195. #ifndef __JUCE_DRAWABLESHAPE_JUCEHEADER__
  51196. #define __JUCE_DRAWABLESHAPE_JUCEHEADER__
  51197. /**
  51198. A base class implementing common functionality for Drawable classes which
  51199. consist of some kind of filled and stroked outline.
  51200. @see DrawablePath, DrawableRectangle
  51201. */
  51202. class JUCE_API DrawableShape : public Drawable
  51203. {
  51204. protected:
  51205. DrawableShape();
  51206. DrawableShape (const DrawableShape&);
  51207. public:
  51208. /** Destructor. */
  51209. ~DrawableShape();
  51210. /** A FillType wrapper that allows the gradient coordinates to be implemented using RelativePoint.
  51211. */
  51212. class RelativeFillType
  51213. {
  51214. public:
  51215. RelativeFillType();
  51216. RelativeFillType (const FillType& fill);
  51217. RelativeFillType (const RelativeFillType&);
  51218. RelativeFillType& operator= (const RelativeFillType&);
  51219. bool operator== (const RelativeFillType&) const;
  51220. bool operator!= (const RelativeFillType&) const;
  51221. bool isDynamic() const;
  51222. bool recalculateCoords (Expression::Scope* scope);
  51223. void writeTo (ValueTree& v, ComponentBuilder::ImageProvider*, UndoManager*) const;
  51224. bool readFrom (const ValueTree& v, ComponentBuilder::ImageProvider*);
  51225. FillType fill;
  51226. RelativePoint gradientPoint1, gradientPoint2, gradientPoint3;
  51227. };
  51228. /** Sets a fill type for the path.
  51229. This colour is used to fill the path - if you don't want the path to be
  51230. filled (e.g. if you're just drawing an outline), set this to a transparent
  51231. colour.
  51232. @see setPath, setStrokeFill
  51233. */
  51234. void setFill (const FillType& newFill);
  51235. /** Sets a fill type for the path.
  51236. This colour is used to fill the path - if you don't want the path to be
  51237. filled (e.g. if you're just drawing an outline), set this to a transparent
  51238. colour.
  51239. @see setPath, setStrokeFill
  51240. */
  51241. void setFill (const RelativeFillType& newFill);
  51242. /** Returns the current fill type.
  51243. @see setFill
  51244. */
  51245. const RelativeFillType& getFill() const noexcept { return mainFill; }
  51246. /** Sets the fill type with which the outline will be drawn.
  51247. @see setFill
  51248. */
  51249. void setStrokeFill (const FillType& newStrokeFill);
  51250. /** Sets the fill type with which the outline will be drawn.
  51251. @see setFill
  51252. */
  51253. void setStrokeFill (const RelativeFillType& newStrokeFill);
  51254. /** Returns the current stroke fill.
  51255. @see setStrokeFill
  51256. */
  51257. const RelativeFillType& getStrokeFill() const noexcept { return strokeFill; }
  51258. /** Changes the properties of the outline that will be drawn around the path.
  51259. If the stroke has 0 thickness, no stroke will be drawn.
  51260. @see setStrokeThickness, setStrokeColour
  51261. */
  51262. void setStrokeType (const PathStrokeType& newStrokeType);
  51263. /** Changes the stroke thickness.
  51264. This is a shortcut for calling setStrokeType.
  51265. */
  51266. void setStrokeThickness (float newThickness);
  51267. /** Returns the current outline style. */
  51268. const PathStrokeType& getStrokeType() const noexcept { return strokeType; }
  51269. /** @internal */
  51270. class FillAndStrokeState : public Drawable::ValueTreeWrapperBase
  51271. {
  51272. public:
  51273. FillAndStrokeState (const ValueTree& state);
  51274. ValueTree getFillState (const Identifier& fillOrStrokeType);
  51275. RelativeFillType getFill (const Identifier& fillOrStrokeType, ComponentBuilder::ImageProvider*) const;
  51276. void setFill (const Identifier& fillOrStrokeType, const RelativeFillType& newFill,
  51277. ComponentBuilder::ImageProvider*, UndoManager*);
  51278. PathStrokeType getStrokeType() const;
  51279. void setStrokeType (const PathStrokeType& newStrokeType, UndoManager*);
  51280. static const Identifier type, colour, colours, fill, stroke, path, jointStyle, capStyle, strokeWidth,
  51281. gradientPoint1, gradientPoint2, gradientPoint3, radial, imageId, imageOpacity;
  51282. };
  51283. /** @internal */
  51284. Rectangle<float> getDrawableBounds() const;
  51285. /** @internal */
  51286. void paint (Graphics& g);
  51287. /** @internal */
  51288. bool hitTest (int x, int y);
  51289. protected:
  51290. /** Called when the cached path should be updated. */
  51291. void pathChanged();
  51292. /** Called when the cached stroke should be updated. */
  51293. void strokeChanged();
  51294. /** True if there's a stroke with a non-zero thickness and non-transparent colour. */
  51295. bool isStrokeVisible() const noexcept;
  51296. /** Updates the details from a FillAndStrokeState object, returning true if something changed. */
  51297. void refreshFillTypes (const FillAndStrokeState& newState, ComponentBuilder::ImageProvider*);
  51298. /** Writes the stroke and fill details to a FillAndStrokeState object. */
  51299. void writeTo (FillAndStrokeState& state, ComponentBuilder::ImageProvider*, UndoManager*) const;
  51300. PathStrokeType strokeType;
  51301. Path path, strokePath;
  51302. private:
  51303. class RelativePositioner;
  51304. RelativeFillType mainFill, strokeFill;
  51305. ScopedPointer<RelativeCoordinatePositionerBase> mainFillPositioner, strokeFillPositioner;
  51306. void setFillInternal (RelativeFillType& fill, const RelativeFillType& newFill,
  51307. ScopedPointer<RelativeCoordinatePositionerBase>& positioner);
  51308. DrawableShape& operator= (const DrawableShape&);
  51309. };
  51310. #endif // __JUCE_DRAWABLESHAPE_JUCEHEADER__
  51311. /*** End of inlined file: juce_DrawableShape.h ***/
  51312. /**
  51313. A drawable object which renders a filled or outlined shape.
  51314. For details on how to change the fill and stroke, see the DrawableShape class.
  51315. @see Drawable, DrawableShape
  51316. */
  51317. class JUCE_API DrawablePath : public DrawableShape
  51318. {
  51319. public:
  51320. /** Creates a DrawablePath. */
  51321. DrawablePath();
  51322. DrawablePath (const DrawablePath& other);
  51323. /** Destructor. */
  51324. ~DrawablePath();
  51325. /** Changes the path that will be drawn.
  51326. @see setFillColour, setStrokeType
  51327. */
  51328. void setPath (const Path& newPath);
  51329. /** Sets the path using a RelativePointPath.
  51330. Calling this will set up a Component::Positioner to automatically update the path
  51331. if any of the points in the source path are dynamic.
  51332. */
  51333. void setPath (const RelativePointPath& newPath);
  51334. /** Returns the current path. */
  51335. const Path& getPath() const;
  51336. /** Returns the current path for the outline. */
  51337. const Path& getStrokePath() const;
  51338. /** @internal */
  51339. Drawable* createCopy() const;
  51340. /** @internal */
  51341. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  51342. /** @internal */
  51343. ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  51344. /** @internal */
  51345. static const Identifier valueTreeType;
  51346. /** Internally-used class for wrapping a DrawablePath's state into a ValueTree. */
  51347. class ValueTreeWrapper : public DrawableShape::FillAndStrokeState
  51348. {
  51349. public:
  51350. ValueTreeWrapper (const ValueTree& state);
  51351. bool usesNonZeroWinding() const;
  51352. void setUsesNonZeroWinding (bool b, UndoManager* undoManager);
  51353. class Element
  51354. {
  51355. public:
  51356. explicit Element (const ValueTree& state);
  51357. ~Element();
  51358. const Identifier getType() const noexcept { return state.getType(); }
  51359. int getNumControlPoints() const noexcept;
  51360. RelativePoint getControlPoint (int index) const;
  51361. Value getControlPointValue (int index, UndoManager*) const;
  51362. RelativePoint getStartPoint() const;
  51363. RelativePoint getEndPoint() const;
  51364. void setControlPoint (int index, const RelativePoint& point, UndoManager*);
  51365. float getLength (Expression::Scope*) const;
  51366. ValueTreeWrapper getParent() const;
  51367. Element getPreviousElement() const;
  51368. String getModeOfEndPoint() const;
  51369. void setModeOfEndPoint (const String& newMode, UndoManager*);
  51370. void convertToLine (UndoManager*);
  51371. void convertToCubic (Expression::Scope*, UndoManager*);
  51372. void convertToPathBreak (UndoManager* undoManager);
  51373. ValueTree insertPoint (const Point<float>& targetPoint, Expression::Scope*, UndoManager*);
  51374. void removePoint (UndoManager* undoManager);
  51375. float findProportionAlongLine (const Point<float>& targetPoint, Expression::Scope*) const;
  51376. static const Identifier mode, startSubPathElement, closeSubPathElement,
  51377. lineToElement, quadraticToElement, cubicToElement;
  51378. static const char* cornerMode;
  51379. static const char* roundedMode;
  51380. static const char* symmetricMode;
  51381. ValueTree state;
  51382. };
  51383. ValueTree getPathState();
  51384. void readFrom (const RelativePointPath& path, UndoManager* undoManager);
  51385. void writeTo (RelativePointPath& path) const;
  51386. static const Identifier nonZeroWinding, point1, point2, point3;
  51387. };
  51388. private:
  51389. ScopedPointer<RelativePointPath> relativePath;
  51390. class RelativePositioner;
  51391. friend class RelativePositioner;
  51392. void applyRelativePath (const RelativePointPath&, Expression::Scope*);
  51393. DrawablePath& operator= (const DrawablePath&);
  51394. JUCE_LEAK_DETECTOR (DrawablePath);
  51395. };
  51396. #endif // __JUCE_DRAWABLEPATH_JUCEHEADER__
  51397. /*** End of inlined file: juce_DrawablePath.h ***/
  51398. #endif
  51399. #ifndef __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  51400. /*** Start of inlined file: juce_DrawableRectangle.h ***/
  51401. #ifndef __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  51402. #define __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  51403. /**
  51404. A Drawable object which draws a rectangle.
  51405. For details on how to change the fill and stroke, see the DrawableShape class.
  51406. @see Drawable, DrawableShape
  51407. */
  51408. class JUCE_API DrawableRectangle : public DrawableShape
  51409. {
  51410. public:
  51411. DrawableRectangle();
  51412. DrawableRectangle (const DrawableRectangle& other);
  51413. /** Destructor. */
  51414. ~DrawableRectangle();
  51415. /** Sets the rectangle's bounds. */
  51416. void setRectangle (const RelativeParallelogram& newBounds);
  51417. /** Returns the rectangle's bounds. */
  51418. const RelativeParallelogram& getRectangle() const noexcept { return bounds; }
  51419. /** Returns the corner size to be used. */
  51420. const RelativePoint& getCornerSize() const noexcept { return cornerSize; }
  51421. /** Sets a new corner size for the rectangle */
  51422. void setCornerSize (const RelativePoint& newSize);
  51423. /** @internal */
  51424. Drawable* createCopy() const;
  51425. /** @internal */
  51426. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  51427. /** @internal */
  51428. ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  51429. /** @internal */
  51430. static const Identifier valueTreeType;
  51431. /** Internally-used class for wrapping a DrawableRectangle's state into a ValueTree. */
  51432. class ValueTreeWrapper : public DrawableShape::FillAndStrokeState
  51433. {
  51434. public:
  51435. ValueTreeWrapper (const ValueTree& state);
  51436. RelativeParallelogram getRectangle() const;
  51437. void setRectangle (const RelativeParallelogram& newBounds, UndoManager*);
  51438. void setCornerSize (const RelativePoint& cornerSize, UndoManager*);
  51439. RelativePoint getCornerSize() const;
  51440. Value getCornerSizeValue (UndoManager*) const;
  51441. static const Identifier topLeft, topRight, bottomLeft, cornerSize;
  51442. };
  51443. private:
  51444. friend class Drawable::Positioner<DrawableRectangle>;
  51445. RelativeParallelogram bounds;
  51446. RelativePoint cornerSize;
  51447. void rebuildPath();
  51448. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  51449. void recalculateCoordinates (Expression::Scope*);
  51450. DrawableRectangle& operator= (const DrawableRectangle&);
  51451. JUCE_LEAK_DETECTOR (DrawableRectangle);
  51452. };
  51453. #endif // __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  51454. /*** End of inlined file: juce_DrawableRectangle.h ***/
  51455. #endif
  51456. #ifndef __JUCE_DRAWABLESHAPE_JUCEHEADER__
  51457. #endif
  51458. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  51459. /*** Start of inlined file: juce_DrawableText.h ***/
  51460. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  51461. #define __JUCE_DRAWABLETEXT_JUCEHEADER__
  51462. /**
  51463. A drawable object which renders a line of text.
  51464. @see Drawable
  51465. */
  51466. class JUCE_API DrawableText : public Drawable
  51467. {
  51468. public:
  51469. /** Creates a DrawableText object. */
  51470. DrawableText();
  51471. DrawableText (const DrawableText& other);
  51472. /** Destructor. */
  51473. ~DrawableText();
  51474. /** Sets the text to display.*/
  51475. void setText (const String& newText);
  51476. /** Sets the colour of the text. */
  51477. void setColour (const Colour& newColour);
  51478. /** Returns the current text colour. */
  51479. const Colour& getColour() const noexcept { return colour; }
  51480. /** Sets the font to use.
  51481. Note that the font height and horizontal scale are actually based upon the position
  51482. of the fontSizeAndScaleAnchor parameter to setBounds(). If applySizeAndScale is true, then
  51483. the height and scale control point will be moved to match the dimensions of the font supplied;
  51484. if it is false, then the new font's height and scale are ignored.
  51485. */
  51486. void setFont (const Font& newFont, bool applySizeAndScale);
  51487. /** Changes the justification of the text within the bounding box. */
  51488. void setJustification (const Justification& newJustification);
  51489. /** Returns the parallelogram that defines the text bounding box. */
  51490. const RelativeParallelogram& getBoundingBox() const noexcept { return bounds; }
  51491. /** Sets the bounding box that contains the text. */
  51492. void setBoundingBox (const RelativeParallelogram& newBounds);
  51493. /** Returns the point within the bounds that defines the font's size and scale. */
  51494. const RelativePoint& getFontSizeControlPoint() const noexcept { return fontSizeControlPoint; }
  51495. /** Sets the control point that defines the font's height and horizontal scale.
  51496. This position is a point within the bounding box parallelogram, whose Y position (relative
  51497. to the parallelogram's origin and possibly distorted shape) specifies the font's height,
  51498. and its X defines the font's horizontal scale.
  51499. */
  51500. void setFontSizeControlPoint (const RelativePoint& newPoint);
  51501. /** @internal */
  51502. void paint (Graphics& g);
  51503. /** @internal */
  51504. Drawable* createCopy() const;
  51505. /** @internal */
  51506. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  51507. /** @internal */
  51508. ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  51509. /** @internal */
  51510. static const Identifier valueTreeType;
  51511. /** @internal */
  51512. Rectangle<float> getDrawableBounds() const;
  51513. /** Internally-used class for wrapping a DrawableText's state into a ValueTree. */
  51514. class ValueTreeWrapper : public Drawable::ValueTreeWrapperBase
  51515. {
  51516. public:
  51517. ValueTreeWrapper (const ValueTree& state);
  51518. String getText() const;
  51519. void setText (const String& newText, UndoManager* undoManager);
  51520. Value getTextValue (UndoManager* undoManager);
  51521. Colour getColour() const;
  51522. void setColour (const Colour& newColour, UndoManager* undoManager);
  51523. Justification getJustification() const;
  51524. void setJustification (const Justification& newJustification, UndoManager* undoManager);
  51525. Font getFont() const;
  51526. void setFont (const Font& newFont, UndoManager* undoManager);
  51527. Value getFontValue (UndoManager* undoManager);
  51528. RelativeParallelogram getBoundingBox() const;
  51529. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  51530. RelativePoint getFontSizeControlPoint() const;
  51531. void setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager);
  51532. static const Identifier text, colour, font, justification, topLeft, topRight, bottomLeft, fontSizeAnchor;
  51533. };
  51534. private:
  51535. RelativeParallelogram bounds;
  51536. RelativePoint fontSizeControlPoint;
  51537. Point<float> resolvedPoints[3];
  51538. Font font, scaledFont;
  51539. String text;
  51540. Colour colour;
  51541. Justification justification;
  51542. friend class Drawable::Positioner<DrawableText>;
  51543. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  51544. void recalculateCoordinates (Expression::Scope*);
  51545. void refreshBounds();
  51546. const AffineTransform getArrangementAndTransform (GlyphArrangement& glyphs) const;
  51547. DrawableText& operator= (const DrawableText&);
  51548. JUCE_LEAK_DETECTOR (DrawableText);
  51549. };
  51550. #endif // __JUCE_DRAWABLETEXT_JUCEHEADER__
  51551. /*** End of inlined file: juce_DrawableText.h ***/
  51552. #endif
  51553. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  51554. #endif
  51555. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  51556. /*** Start of inlined file: juce_GlowEffect.h ***/
  51557. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  51558. #define __JUCE_GLOWEFFECT_JUCEHEADER__
  51559. /**
  51560. A component effect that adds a coloured blur around the component's contents.
  51561. (This will only work on non-opaque components).
  51562. @see Component::setComponentEffect, DropShadowEffect
  51563. */
  51564. class JUCE_API GlowEffect : public ImageEffectFilter
  51565. {
  51566. public:
  51567. /** Creates a default 'glow' effect.
  51568. To customise its appearance, use the setGlowProperties() method.
  51569. */
  51570. GlowEffect();
  51571. /** Destructor. */
  51572. ~GlowEffect();
  51573. /** Sets the glow's radius and colour.
  51574. The radius is how large the blur should be, and the colour is
  51575. used to render it (for a less intense glow, lower the colour's
  51576. opacity).
  51577. */
  51578. void setGlowProperties (float newRadius,
  51579. const Colour& newColour);
  51580. /** @internal */
  51581. void applyEffect (Image& sourceImage, Graphics& destContext, float alpha);
  51582. private:
  51583. float radius;
  51584. Colour colour;
  51585. JUCE_LEAK_DETECTOR (GlowEffect);
  51586. };
  51587. #endif // __JUCE_GLOWEFFECT_JUCEHEADER__
  51588. /*** End of inlined file: juce_GlowEffect.h ***/
  51589. #endif
  51590. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  51591. #endif
  51592. #ifndef __JUCE_CUSTOMTYPEFACE_JUCEHEADER__
  51593. /*** Start of inlined file: juce_CustomTypeface.h ***/
  51594. #ifndef __JUCE_CUSTOMTYPEFACE_JUCEHEADER__
  51595. #define __JUCE_CUSTOMTYPEFACE_JUCEHEADER__
  51596. class InputStream;
  51597. class OutputStream;
  51598. /**
  51599. A typeface that can be populated with custom glyphs.
  51600. You can create a CustomTypeface if you need one that contains your own glyphs,
  51601. or if you need to load a typeface from a Juce-formatted binary stream.
  51602. If you want to create a copy of a native face, you can use addGlyphsFromOtherTypeface()
  51603. to copy glyphs into this face.
  51604. @see Typeface, Font
  51605. */
  51606. class JUCE_API CustomTypeface : public Typeface
  51607. {
  51608. public:
  51609. /** Creates a new, empty typeface. */
  51610. CustomTypeface();
  51611. /** Loads a typeface from a previously saved stream.
  51612. The stream must have been created by writeToStream().
  51613. @see writeToStream
  51614. */
  51615. explicit CustomTypeface (InputStream& serialisedTypefaceStream);
  51616. /** Destructor. */
  51617. ~CustomTypeface();
  51618. /** Resets this typeface, deleting all its glyphs and settings. */
  51619. void clear();
  51620. /** Sets the vital statistics for the typeface.
  51621. @param name the typeface's name
  51622. @param ascent the ascent - this is normalised to a height of 1.0 and this is
  51623. the value that will be returned by Typeface::getAscent(). The
  51624. descent is assumed to be (1.0 - ascent)
  51625. @param isBold should be true if the typeface is bold
  51626. @param isItalic should be true if the typeface is italic
  51627. @param defaultCharacter the character to be used as a replacement if there's
  51628. no glyph available for the character that's being drawn
  51629. */
  51630. void setCharacteristics (const String& name, float ascent,
  51631. bool isBold, bool isItalic,
  51632. juce_wchar defaultCharacter) noexcept;
  51633. /** Adds a glyph to the typeface.
  51634. The path that is passed in is normalised so that the font height is 1.0, and its
  51635. origin is the anchor point of the character on its baseline.
  51636. The width is the nominal width of the character, and any extra kerning values that
  51637. are specified will be added to this width.
  51638. */
  51639. void addGlyph (juce_wchar character, const Path& path, float width) noexcept;
  51640. /** Specifies an extra kerning amount to be used between a pair of characters.
  51641. The amount will be added to the nominal width of the first character when laying out a string.
  51642. */
  51643. void addKerningPair (juce_wchar char1, juce_wchar char2, float extraAmount) noexcept;
  51644. /** Adds a range of glyphs from another typeface.
  51645. This will attempt to pull in the paths and kerning information from another typeface and
  51646. add it to this one.
  51647. */
  51648. void addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) noexcept;
  51649. /** Saves this typeface as a Juce-formatted font file.
  51650. A CustomTypeface can be created to reload the data that is written - see the CustomTypeface
  51651. constructor.
  51652. */
  51653. bool writeToStream (OutputStream& outputStream);
  51654. // The following methods implement the basic Typeface behaviour.
  51655. float getAscent() const;
  51656. float getDescent() const;
  51657. float getStringWidth (const String& text);
  51658. void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets);
  51659. bool getOutlineForGlyph (int glyphNumber, Path& path);
  51660. EdgeTable* getEdgeTableForGlyph (int glyphNumber, const AffineTransform& transform);
  51661. protected:
  51662. juce_wchar defaultCharacter;
  51663. float ascent;
  51664. bool isBold, isItalic;
  51665. /** If a subclass overrides this, it can load glyphs into the font on-demand.
  51666. When methods such as getGlyphPositions() or getOutlineForGlyph() are asked for a
  51667. particular character and there's no corresponding glyph, they'll call this
  51668. method so that a subclass can try to add that glyph, returning true if it
  51669. manages to do so.
  51670. */
  51671. virtual bool loadGlyphIfPossible (juce_wchar characterNeeded);
  51672. private:
  51673. class GlyphInfo;
  51674. friend class OwnedArray<GlyphInfo>;
  51675. OwnedArray <GlyphInfo> glyphs;
  51676. short lookupTable [128];
  51677. GlyphInfo* findGlyph (const juce_wchar character, bool loadIfNeeded) noexcept;
  51678. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomTypeface);
  51679. };
  51680. #endif // __JUCE_CUSTOMTYPEFACE_JUCEHEADER__
  51681. /*** End of inlined file: juce_CustomTypeface.h ***/
  51682. #endif
  51683. #ifndef __JUCE_FONT_JUCEHEADER__
  51684. #endif
  51685. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  51686. #endif
  51687. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  51688. #endif
  51689. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  51690. #endif
  51691. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  51692. #endif
  51693. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  51694. #endif
  51695. #ifndef __JUCE_LINE_JUCEHEADER__
  51696. #endif
  51697. #ifndef __JUCE_PATH_JUCEHEADER__
  51698. #endif
  51699. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  51700. /*** Start of inlined file: juce_PathIterator.h ***/
  51701. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  51702. #define __JUCE_PATHITERATOR_JUCEHEADER__
  51703. /**
  51704. Flattens a Path object into a series of straight-line sections.
  51705. Use one of these to iterate through a Path object, and it will convert
  51706. all the curves into line sections so it's easy to render or perform
  51707. geometric operations on.
  51708. @see Path
  51709. */
  51710. class JUCE_API PathFlatteningIterator
  51711. {
  51712. public:
  51713. /** Creates a PathFlatteningIterator.
  51714. After creation, use the next() method to initialise the fields in the
  51715. object with the first line's position.
  51716. @param path the path to iterate along
  51717. @param transform a transform to apply to each point in the path being iterated
  51718. @param tolerance the amount by which the curves are allowed to deviate from the lines
  51719. into which they are being broken down - a higher tolerance contains
  51720. less lines, so can be generated faster, but will be less smooth.
  51721. */
  51722. PathFlatteningIterator (const Path& path,
  51723. const AffineTransform& transform = AffineTransform::identity,
  51724. float tolerance = defaultTolerance);
  51725. /** Destructor. */
  51726. ~PathFlatteningIterator();
  51727. /** Fetches the next line segment from the path.
  51728. This will update the member variables x1, y1, x2, y2, subPathIndex and closesSubPath
  51729. so that they describe the new line segment.
  51730. @returns false when there are no more lines to fetch.
  51731. */
  51732. bool next();
  51733. float x1; /**< The x position of the start of the current line segment. */
  51734. float y1; /**< The y position of the start of the current line segment. */
  51735. float x2; /**< The x position of the end of the current line segment. */
  51736. float y2; /**< The y position of the end of the current line segment. */
  51737. /** Indicates whether the current line segment is closing a sub-path.
  51738. If the current line is the one that connects the end of a sub-path
  51739. back to the start again, this will be true.
  51740. */
  51741. bool closesSubPath;
  51742. /** The index of the current line within the current sub-path.
  51743. E.g. you can use this to see whether the line is the first one in the
  51744. subpath by seeing if it's 0.
  51745. */
  51746. int subPathIndex;
  51747. /** Returns true if the current segment is the last in the current sub-path. */
  51748. bool isLastInSubpath() const noexcept;
  51749. /** This is the default value that should be used for the tolerance value (see the constructor parameters). */
  51750. static const float defaultTolerance;
  51751. private:
  51752. const Path& path;
  51753. const AffineTransform transform;
  51754. float* points;
  51755. const float toleranceSquared;
  51756. float subPathCloseX, subPathCloseY;
  51757. const bool isIdentityTransform;
  51758. HeapBlock <float> stackBase;
  51759. float* stackPos;
  51760. size_t index, stackSize;
  51761. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PathFlatteningIterator);
  51762. };
  51763. #endif // __JUCE_PATHITERATOR_JUCEHEADER__
  51764. /*** End of inlined file: juce_PathIterator.h ***/
  51765. #endif
  51766. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  51767. #endif
  51768. #ifndef __JUCE_POINT_JUCEHEADER__
  51769. #endif
  51770. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  51771. #endif
  51772. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  51773. #endif
  51774. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  51775. /*** Start of inlined file: juce_CameraDevice.h ***/
  51776. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  51777. #define __JUCE_CAMERADEVICE_JUCEHEADER__
  51778. #if JUCE_USE_CAMERA || DOXYGEN
  51779. /**
  51780. Controls any video capture devices that might be available.
  51781. Use getAvailableDevices() to list the devices that are attached to the
  51782. system, then call openDevice to open one for use. Once you have a CameraDevice
  51783. object, you can get a viewer component from it, and use its methods to
  51784. stream to a file or capture still-frames.
  51785. */
  51786. class JUCE_API CameraDevice
  51787. {
  51788. public:
  51789. /** Destructor. */
  51790. virtual ~CameraDevice();
  51791. /** Returns a list of the available cameras on this machine.
  51792. You can open one of these devices by calling openDevice().
  51793. */
  51794. static StringArray getAvailableDevices();
  51795. /** Opens a camera device.
  51796. The index parameter indicates which of the items returned by getAvailableDevices()
  51797. to open.
  51798. The size constraints allow the method to choose between different resolutions if
  51799. the camera supports this. If the resolution cam't be specified (e.g. on the Mac)
  51800. then these will be ignored.
  51801. */
  51802. static CameraDevice* openDevice (int deviceIndex,
  51803. int minWidth = 128, int minHeight = 64,
  51804. int maxWidth = 1024, int maxHeight = 768);
  51805. /** Returns the name of this device */
  51806. String getName() const { return name; }
  51807. /** Creates a component that can be used to display a preview of the
  51808. video from this camera.
  51809. */
  51810. Component* createViewerComponent();
  51811. /** Starts recording video to the specified file.
  51812. You should use getFileExtension() to find out the correct extension to
  51813. use for your filename.
  51814. If the file exists, it will be deleted before the recording starts.
  51815. This method may not start recording instantly, so if you need to know the
  51816. exact time at which the file begins, you can call getTimeOfFirstRecordedFrame()
  51817. after the recording has finished.
  51818. The quality parameter can be 0, 1, or 2, to indicate low, medium, or high. It may
  51819. or may not be used, depending on the driver.
  51820. */
  51821. void startRecordingToFile (const File& file, int quality = 2);
  51822. /** Stops recording, after a call to startRecordingToFile().
  51823. */
  51824. void stopRecording();
  51825. /** Returns the file extension that should be used for the files
  51826. that you pass to startRecordingToFile().
  51827. This may be platform-specific, e.g. ".mov" or ".avi".
  51828. */
  51829. static String getFileExtension();
  51830. /** After calling stopRecording(), this method can be called to return the timestamp
  51831. of the first frame that was written to the file.
  51832. */
  51833. Time getTimeOfFirstRecordedFrame() const;
  51834. /**
  51835. Receives callbacks with images from a CameraDevice.
  51836. @see CameraDevice::addListener
  51837. */
  51838. class JUCE_API Listener
  51839. {
  51840. public:
  51841. Listener() {}
  51842. virtual ~Listener() {}
  51843. /** This method is called when a new image arrives.
  51844. This may be called by any thread, so be careful about thread-safety,
  51845. and make sure that you process the data as quickly as possible to
  51846. avoid glitching!
  51847. */
  51848. virtual void imageReceived (const Image& image) = 0;
  51849. };
  51850. /** Adds a listener to receive images from the camera.
  51851. Be very careful not to delete the listener without first removing it by calling
  51852. removeListener().
  51853. */
  51854. void addListener (Listener* listenerToAdd);
  51855. /** Removes a listener that was previously added with addListener().
  51856. */
  51857. void removeListener (Listener* listenerToRemove);
  51858. protected:
  51859. #ifndef DOXYGEN
  51860. CameraDevice (const String& name, int index);
  51861. #endif
  51862. private:
  51863. void* internal;
  51864. bool isRecording;
  51865. String name;
  51866. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CameraDevice);
  51867. };
  51868. /** This typedef is just for compatibility with old code - newer code should use the CameraDevice::Listener class directly. */
  51869. typedef CameraDevice::Listener CameraImageListener;
  51870. #endif
  51871. #endif // __JUCE_CAMERADEVICE_JUCEHEADER__
  51872. /*** End of inlined file: juce_CameraDevice.h ***/
  51873. #endif
  51874. #ifndef __JUCE_IMAGE_JUCEHEADER__
  51875. #endif
  51876. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  51877. /*** Start of inlined file: juce_ImageCache.h ***/
  51878. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  51879. #define __JUCE_IMAGECACHE_JUCEHEADER__
  51880. /**
  51881. A global cache of images that have been loaded from files or memory.
  51882. If you're loading an image and may need to use the image in more than one
  51883. place, this is used to allow the same image to be shared rather than loading
  51884. multiple copies into memory.
  51885. Another advantage is that after images are released, they will be kept in
  51886. memory for a few seconds before it is actually deleted, so if you're repeatedly
  51887. loading/deleting the same image, it'll reduce the chances of having to reload it
  51888. each time.
  51889. @see Image, ImageFileFormat
  51890. */
  51891. class JUCE_API ImageCache
  51892. {
  51893. public:
  51894. /** Loads an image from a file, (or just returns the image if it's already cached).
  51895. If the cache already contains an image that was loaded from this file,
  51896. that image will be returned. Otherwise, this method will try to load the
  51897. file, add it to the cache, and return it.
  51898. Remember that the image returned is shared, so drawing into it might
  51899. affect other things that are using it! If you want to draw on it, first
  51900. call Image::duplicateIfShared()
  51901. @param file the file to try to load
  51902. @returns the image, or null if it there was an error loading it
  51903. @see getFromMemory, getFromCache, ImageFileFormat::loadFrom
  51904. */
  51905. static Image getFromFile (const File& file);
  51906. /** Loads an image from an in-memory image file, (or just returns the image if it's already cached).
  51907. If the cache already contains an image that was loaded from this block of memory,
  51908. that image will be returned. Otherwise, this method will try to load the
  51909. file, add it to the cache, and return it.
  51910. Remember that the image returned is shared, so drawing into it might
  51911. affect other things that are using it! If you want to draw on it, first
  51912. call Image::duplicateIfShared()
  51913. @param imageData the block of memory containing the image data
  51914. @param dataSize the data size in bytes
  51915. @returns the image, or an invalid image if it there was an error loading it
  51916. @see getFromMemory, getFromCache, ImageFileFormat::loadFrom
  51917. */
  51918. static Image getFromMemory (const void* imageData, int dataSize);
  51919. /** Checks the cache for an image with a particular hashcode.
  51920. If there's an image in the cache with this hashcode, it will be returned,
  51921. otherwise it will return an invalid image.
  51922. @param hashCode the hash code that was associated with the image by addImageToCache()
  51923. @see addImageToCache
  51924. */
  51925. static Image getFromHashCode (int64 hashCode);
  51926. /** Adds an image to the cache with a user-defined hash-code.
  51927. The image passed-in will be referenced (not copied) by the cache, so it's probably
  51928. a good idea not to draw into it after adding it, otherwise this will affect all
  51929. instances of it that may be in use.
  51930. @param image the image to add
  51931. @param hashCode the hash-code to associate with it
  51932. @see getFromHashCode
  51933. */
  51934. static void addImageToCache (const Image& image, int64 hashCode);
  51935. /** Changes the amount of time before an unused image will be removed from the cache.
  51936. By default this is about 5 seconds.
  51937. */
  51938. static void setCacheTimeout (int millisecs);
  51939. private:
  51940. class Pimpl;
  51941. friend class Pimpl;
  51942. ImageCache();
  51943. ~ImageCache();
  51944. JUCE_DECLARE_NON_COPYABLE (ImageCache);
  51945. };
  51946. #endif // __JUCE_IMAGECACHE_JUCEHEADER__
  51947. /*** End of inlined file: juce_ImageCache.h ***/
  51948. #endif
  51949. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  51950. /*** Start of inlined file: juce_ImageConvolutionKernel.h ***/
  51951. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  51952. #define __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  51953. /**
  51954. Represents a filter kernel to use in convoluting an image.
  51955. @see Image::applyConvolution
  51956. */
  51957. class JUCE_API ImageConvolutionKernel
  51958. {
  51959. public:
  51960. /** Creates an empty convulution kernel.
  51961. @param size the length of each dimension of the kernel, so e.g. if the size
  51962. is 5, it will create a 5x5 kernel
  51963. */
  51964. ImageConvolutionKernel (int size);
  51965. /** Destructor. */
  51966. ~ImageConvolutionKernel();
  51967. /** Resets all values in the kernel to zero. */
  51968. void clear();
  51969. /** Returns one of the kernel values. */
  51970. float getKernelValue (int x, int y) const noexcept;
  51971. /** Sets the value of a specific cell in the kernel.
  51972. The x and y parameters must be in the range 0 < x < getKernelSize().
  51973. @see setOverallSum
  51974. */
  51975. void setKernelValue (int x, int y, float value) noexcept;
  51976. /** Rescales all values in the kernel to make the total add up to a fixed value.
  51977. This will multiply all values in the kernel by (desiredTotalSum / currentTotalSum).
  51978. */
  51979. void setOverallSum (float desiredTotalSum);
  51980. /** Multiplies all values in the kernel by a value. */
  51981. void rescaleAllValues (float multiplier);
  51982. /** Intialises the kernel for a gaussian blur.
  51983. @param blurRadius this may be larger or smaller than the kernel's actual
  51984. size but this will obviously be wasteful or clip at the
  51985. edges. Ideally the kernel should be just larger than
  51986. (blurRadius * 2).
  51987. */
  51988. void createGaussianBlur (float blurRadius);
  51989. /** Returns the size of the kernel.
  51990. E.g. if it's a 3x3 kernel, this returns 3.
  51991. */
  51992. int getKernelSize() const { return size; }
  51993. /** Applies the kernel to an image.
  51994. @param destImage the image that will receive the resultant convoluted pixels.
  51995. @param sourceImage the source image to read from - this can be the same image as
  51996. the destination, but if different, it must be exactly the same
  51997. size and format.
  51998. @param destinationArea the region of the image to apply the filter to
  51999. */
  52000. void applyToImage (Image& destImage,
  52001. const Image& sourceImage,
  52002. const Rectangle<int>& destinationArea) const;
  52003. private:
  52004. HeapBlock <float> values;
  52005. const int size;
  52006. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImageConvolutionKernel);
  52007. };
  52008. #endif // __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  52009. /*** End of inlined file: juce_ImageConvolutionKernel.h ***/
  52010. #endif
  52011. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  52012. /*** Start of inlined file: juce_ImageFileFormat.h ***/
  52013. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  52014. #define __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  52015. /**
  52016. Base-class for codecs that can read and write image file formats such
  52017. as PNG, JPEG, etc.
  52018. This class also contains static methods to make it easy to load images
  52019. from files, streams or from memory.
  52020. @see Image, ImageCache
  52021. */
  52022. class JUCE_API ImageFileFormat
  52023. {
  52024. protected:
  52025. /** Creates an ImageFormat. */
  52026. ImageFileFormat() {}
  52027. public:
  52028. /** Destructor. */
  52029. virtual ~ImageFileFormat() {}
  52030. /** Returns a description of this file format.
  52031. E.g. "JPEG", "PNG"
  52032. */
  52033. virtual String getFormatName() = 0;
  52034. /** Returns true if the given stream seems to contain data that this format
  52035. understands.
  52036. The format class should only read the first few bytes of the stream and sniff
  52037. for header bytes that it understands.
  52038. @see decodeImage
  52039. */
  52040. virtual bool canUnderstand (InputStream& input) = 0;
  52041. /** Tries to decode and return an image from the given stream.
  52042. This will be called for an image format after calling its canUnderStand() method
  52043. to see if it can handle the stream.
  52044. @param input the stream to read the data from. The stream will be positioned
  52045. at the start of the image data (but this may not necessarily
  52046. be position 0)
  52047. @returns the image that was decoded, or an invalid image if it fails.
  52048. @see loadFrom
  52049. */
  52050. virtual Image decodeImage (InputStream& input) = 0;
  52051. /** Attempts to write an image to a stream.
  52052. To specify extra information like encoding quality, there will be appropriate parameters
  52053. in the subclasses of the specific file types.
  52054. @returns true if it nothing went wrong.
  52055. */
  52056. virtual bool writeImageToStream (const Image& sourceImage,
  52057. OutputStream& destStream) = 0;
  52058. /** Tries the built-in decoders to see if it can find one to read this stream.
  52059. There are currently built-in decoders for PNG, JPEG and GIF formats.
  52060. The object that is returned should not be deleted by the caller.
  52061. @see canUnderstand, decodeImage, loadFrom
  52062. */
  52063. static ImageFileFormat* findImageFormatForStream (InputStream& input);
  52064. /** Tries to load an image from a stream.
  52065. This will use the findImageFormatForStream() method to locate a suitable
  52066. codec, and use that to load the image.
  52067. @returns the image that was decoded, or an invalid image if it fails.
  52068. */
  52069. static Image loadFrom (InputStream& input);
  52070. /** Tries to load an image from a file.
  52071. This will use the findImageFormatForStream() method to locate a suitable
  52072. codec, and use that to load the image.
  52073. @returns the image that was decoded, or an invalid image if it fails.
  52074. */
  52075. static Image loadFrom (const File& file);
  52076. /** Tries to load an image from a block of raw image data.
  52077. This will use the findImageFormatForStream() method to locate a suitable
  52078. codec, and use that to load the image.
  52079. @returns the image that was decoded, or an invalid image if it fails.
  52080. */
  52081. static Image loadFrom (const void* rawData,
  52082. const int numBytesOfData);
  52083. };
  52084. /**
  52085. A subclass of ImageFileFormat for reading and writing PNG files.
  52086. @see ImageFileFormat, JPEGImageFormat
  52087. */
  52088. class JUCE_API PNGImageFormat : public ImageFileFormat
  52089. {
  52090. public:
  52091. PNGImageFormat();
  52092. ~PNGImageFormat();
  52093. String getFormatName();
  52094. bool canUnderstand (InputStream& input);
  52095. Image decodeImage (InputStream& input);
  52096. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  52097. };
  52098. /**
  52099. A subclass of ImageFileFormat for reading and writing JPEG files.
  52100. @see ImageFileFormat, PNGImageFormat
  52101. */
  52102. class JUCE_API JPEGImageFormat : public ImageFileFormat
  52103. {
  52104. public:
  52105. JPEGImageFormat();
  52106. ~JPEGImageFormat();
  52107. /** Specifies the quality to be used when writing a JPEG file.
  52108. @param newQuality a value 0 to 1.0, where 0 is low quality, 1.0 is best, or
  52109. any negative value is "default" quality
  52110. */
  52111. void setQuality (float newQuality);
  52112. String getFormatName();
  52113. bool canUnderstand (InputStream& input);
  52114. Image decodeImage (InputStream& input);
  52115. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  52116. private:
  52117. float quality;
  52118. };
  52119. /**
  52120. A subclass of ImageFileFormat for reading GIF files.
  52121. @see ImageFileFormat, PNGImageFormat, JPEGImageFormat
  52122. */
  52123. class JUCE_API GIFImageFormat : public ImageFileFormat
  52124. {
  52125. public:
  52126. GIFImageFormat();
  52127. ~GIFImageFormat();
  52128. String getFormatName();
  52129. bool canUnderstand (InputStream& input);
  52130. Image decodeImage (InputStream& input);
  52131. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  52132. };
  52133. #endif // __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  52134. /*** End of inlined file: juce_ImageFileFormat.h ***/
  52135. #endif
  52136. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  52137. #endif
  52138. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  52139. /*** Start of inlined file: juce_FileBasedDocument.h ***/
  52140. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  52141. #define __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  52142. /**
  52143. A class to take care of the logic involved with the loading/saving of some kind
  52144. of document.
  52145. There's quite a lot of tedious logic involved in writing all the load/save/save-as
  52146. functions you need for documents that get saved to a file, so this class attempts
  52147. to abstract most of the boring stuff.
  52148. Your subclass should just implement all the pure virtual methods, and you can
  52149. then use the higher-level public methods to do the load/save dialogs, to warn the user
  52150. about overwriting files, etc.
  52151. The document object keeps track of whether it has changed since it was last saved or
  52152. loaded, so when you change something, call its changed() method. This will set a
  52153. flag so it knows it needs saving, and will also broadcast a change message using the
  52154. ChangeBroadcaster base class.
  52155. @see ChangeBroadcaster
  52156. */
  52157. class JUCE_API FileBasedDocument : public ChangeBroadcaster
  52158. {
  52159. public:
  52160. /** Creates a FileBasedDocument.
  52161. @param fileExtension the extension to use when loading/saving files, e.g. ".doc"
  52162. @param fileWildCard the wildcard to use in file dialogs, e.g. "*.doc"
  52163. @param openFileDialogTitle the title to show on an open-file dialog, e.g. "Choose a file to open.."
  52164. @param saveFileDialogTitle the title to show on an save-file dialog, e.g. "Choose a file to save as.."
  52165. */
  52166. FileBasedDocument (const String& fileExtension,
  52167. const String& fileWildCard,
  52168. const String& openFileDialogTitle,
  52169. const String& saveFileDialogTitle);
  52170. /** Destructor. */
  52171. virtual ~FileBasedDocument();
  52172. /** Returns true if the changed() method has been called since the file was
  52173. last saved or loaded.
  52174. @see resetChangedFlag, changed
  52175. */
  52176. bool hasChangedSinceSaved() const { return changedSinceSave; }
  52177. /** Called to indicate that the document has changed and needs saving.
  52178. This method will also trigger a change message to be sent out using the
  52179. ChangeBroadcaster base class.
  52180. After calling the method, the hasChangedSinceSaved() method will return true, until
  52181. it is reset either by saving to a file or using the resetChangedFlag() method.
  52182. @see hasChangedSinceSaved, resetChangedFlag
  52183. */
  52184. virtual void changed();
  52185. /** Sets the state of the 'changed' flag.
  52186. The 'changed' flag is set to true when the changed() method is called - use this method
  52187. to reset it or to set it without also broadcasting a change message.
  52188. @see changed, hasChangedSinceSaved
  52189. */
  52190. void setChangedFlag (bool hasChanged);
  52191. /** Tries to open a file.
  52192. If the file opens correctly, the document's file (see the getFile() method) is set
  52193. to this new one; if it fails, the document's file is left unchanged, and optionally
  52194. a message box is shown telling the user there was an error.
  52195. @returns true if the new file loaded successfully
  52196. @see loadDocument, loadFromUserSpecifiedFile
  52197. */
  52198. bool loadFrom (const File& fileToLoadFrom,
  52199. bool showMessageOnFailure);
  52200. /** Asks the user for a file and tries to load it.
  52201. This will pop up a dialog box using the title, file extension and
  52202. wildcard specified in the document's constructor, and asks the user
  52203. for a file. If they pick one, the loadFrom() method is used to
  52204. try to load it, optionally showing a message if it fails.
  52205. @returns true if a file was loaded; false if the user cancelled or if they
  52206. picked a file which failed to load correctly
  52207. @see loadFrom
  52208. */
  52209. bool loadFromUserSpecifiedFile (bool showMessageOnFailure);
  52210. /** A set of possible outcomes of one of the save() methods
  52211. */
  52212. enum SaveResult
  52213. {
  52214. savedOk = 0, /**< indicates that a file was saved successfully. */
  52215. userCancelledSave, /**< indicates that the user aborted the save operation. */
  52216. failedToWriteToFile /**< indicates that it tried to write to a file but this failed. */
  52217. };
  52218. /** Tries to save the document to the last file it was saved or loaded from.
  52219. This will always try to write to the file, even if the document isn't flagged as
  52220. having changed.
  52221. @param askUserForFileIfNotSpecified if there's no file currently specified and this is
  52222. true, it will prompt the user to pick a file, as if
  52223. saveAsInteractive() was called.
  52224. @param showMessageOnFailure if true it will show a warning message when if the
  52225. save operation fails
  52226. @see saveIfNeededAndUserAgrees, saveAs, saveAsInteractive
  52227. */
  52228. SaveResult save (bool askUserForFileIfNotSpecified,
  52229. bool showMessageOnFailure);
  52230. /** If the file needs saving, it'll ask the user if that's what they want to do, and save
  52231. it if they say yes.
  52232. If you've got a document open and want to close it (e.g. to quit the app), this is the
  52233. method to call.
  52234. If the document doesn't need saving it'll return the value savedOk so
  52235. you can go ahead and delete the document.
  52236. If it does need saving it'll prompt the user, and if they say "discard changes" it'll
  52237. return savedOk, so again, you can safely delete the document.
  52238. If the user clicks "cancel", it'll return userCancelledSave, so if you can abort the
  52239. close-document operation.
  52240. And if they click "save changes", it'll try to save and either return savedOk, or
  52241. failedToWriteToFile if there was a problem.
  52242. @see save, saveAs, saveAsInteractive
  52243. */
  52244. SaveResult saveIfNeededAndUserAgrees();
  52245. /** Tries to save the document to a specified file.
  52246. If this succeeds, it'll also change the document's internal file (as returned by
  52247. the getFile() method). If it fails, the file will be left unchanged.
  52248. @param newFile the file to try to write to
  52249. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  52250. the user first if they want to overwrite it
  52251. @param askUserForFileIfNotSpecified if the file is non-existent and this is true, it'll
  52252. use the saveAsInteractive() method to ask the user for a
  52253. filename
  52254. @param showMessageOnFailure if true and the write operation fails, it'll show
  52255. a message box to warn the user
  52256. @see saveIfNeededAndUserAgrees, save, saveAsInteractive
  52257. */
  52258. SaveResult saveAs (const File& newFile,
  52259. bool warnAboutOverwritingExistingFiles,
  52260. bool askUserForFileIfNotSpecified,
  52261. bool showMessageOnFailure);
  52262. /** Prompts the user for a filename and tries to save to it.
  52263. This will pop up a dialog box using the title, file extension and
  52264. wildcard specified in the document's constructor, and asks the user
  52265. for a file. If they pick one, the saveAs() method is used to try to save
  52266. to this file.
  52267. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  52268. the user first if they want to overwrite it
  52269. @see saveIfNeededAndUserAgrees, save, saveAs
  52270. */
  52271. SaveResult saveAsInteractive (bool warnAboutOverwritingExistingFiles);
  52272. /** Returns the file that this document was last successfully saved or loaded from.
  52273. When the document object is created, this will be set to File::nonexistent.
  52274. It is changed when one of the load or save methods is used, or when setFile()
  52275. is used to explicitly set it.
  52276. */
  52277. const File& getFile() const { return documentFile; }
  52278. /** Sets the file that this document thinks it was loaded from.
  52279. This won't actually load anything - it just changes the file stored internally.
  52280. @see getFile
  52281. */
  52282. void setFile (const File& newFile);
  52283. protected:
  52284. /** Overload this to return the title of the document.
  52285. This is used in message boxes, filenames and file choosers, so it should be
  52286. something sensible.
  52287. */
  52288. virtual const String getDocumentTitle() = 0;
  52289. /** This method should try to load your document from the given file.
  52290. If it fails, it should return an error message. If it succeeds, it should return
  52291. an empty string.
  52292. */
  52293. virtual const String loadDocument (const File& file) = 0;
  52294. /** This method should try to write your document to the given file.
  52295. If it fails, it should return an error message. If it succeeds, it should return
  52296. an empty string.
  52297. */
  52298. virtual const String saveDocument (const File& file) = 0;
  52299. /** This is used for dialog boxes to make them open at the last folder you
  52300. were using.
  52301. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  52302. the last document that was used - you might want to store this value
  52303. in a static variable, or even in your application's properties. It should
  52304. be a global setting rather than a property of this object.
  52305. This method works very well in conjunction with a RecentlyOpenedFilesList
  52306. object to manage your recent-files list.
  52307. As a default value, it's ok to return File::nonexistent, and the document
  52308. object will use a sensible one instead.
  52309. @see RecentlyOpenedFilesList
  52310. */
  52311. virtual const File getLastDocumentOpened() = 0;
  52312. /** This is used for dialog boxes to make them open at the last folder you
  52313. were using.
  52314. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  52315. the last document that was used - you might want to store this value
  52316. in a static variable, or even in your application's properties. It should
  52317. be a global setting rather than a property of this object.
  52318. This method works very well in conjunction with a RecentlyOpenedFilesList
  52319. object to manage your recent-files list.
  52320. @see RecentlyOpenedFilesList
  52321. */
  52322. virtual void setLastDocumentOpened (const File& file) = 0;
  52323. private:
  52324. File documentFile;
  52325. bool changedSinceSave;
  52326. String fileExtension, fileWildcard, openFileDialogTitle, saveFileDialogTitle;
  52327. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileBasedDocument);
  52328. };
  52329. #endif // __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  52330. /*** End of inlined file: juce_FileBasedDocument.h ***/
  52331. #endif
  52332. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  52333. #endif
  52334. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  52335. /*** Start of inlined file: juce_RecentlyOpenedFilesList.h ***/
  52336. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  52337. #define __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  52338. /**
  52339. Manages a set of files for use as a list of recently-opened documents.
  52340. This is a handy class for holding your list of recently-opened documents, with
  52341. helpful methods for things like purging any non-existent files, automatically
  52342. adding them to a menu, and making persistence easy.
  52343. @see File, FileBasedDocument
  52344. */
  52345. class JUCE_API RecentlyOpenedFilesList
  52346. {
  52347. public:
  52348. /** Creates an empty list.
  52349. */
  52350. RecentlyOpenedFilesList();
  52351. /** Destructor. */
  52352. ~RecentlyOpenedFilesList();
  52353. /** Sets a limit for the number of files that will be stored in the list.
  52354. When addFile() is called, then if there is no more space in the list, the
  52355. least-recently added file will be dropped.
  52356. @see getMaxNumberOfItems
  52357. */
  52358. void setMaxNumberOfItems (int newMaxNumber);
  52359. /** Returns the number of items that this list will store.
  52360. @see setMaxNumberOfItems
  52361. */
  52362. int getMaxNumberOfItems() const noexcept { return maxNumberOfItems; }
  52363. /** Returns the number of files in the list.
  52364. The most recently added file is always at index 0.
  52365. */
  52366. int getNumFiles() const;
  52367. /** Returns one of the files in the list.
  52368. The most recently added file is always at index 0.
  52369. */
  52370. File getFile (int index) const;
  52371. /** Returns an array of all the absolute pathnames in the list.
  52372. */
  52373. const StringArray& getAllFilenames() const noexcept { return files; }
  52374. /** Clears all the files from the list. */
  52375. void clear();
  52376. /** Adds a file to the list.
  52377. The file will be added at index 0. If this file is already in the list, it will
  52378. be moved up to index 0, but a file can only appear once in the list.
  52379. If the list already contains the maximum number of items that is permitted, the
  52380. least-recently added file will be dropped from the end.
  52381. */
  52382. void addFile (const File& file);
  52383. /** Removes a file from the list. */
  52384. void removeFile (const File& file);
  52385. /** Checks each of the files in the list, removing any that don't exist.
  52386. You might want to call this after reloading a list of files, or before putting them
  52387. on a menu.
  52388. */
  52389. void removeNonExistentFiles();
  52390. /** Adds entries to a menu, representing each of the files in the list.
  52391. This is handy for creating an "open recent file..." menu in your app. The
  52392. menu items are numbered consecutively starting with the baseItemId value,
  52393. and can either be added as complete pathnames, or just the last part of the
  52394. filename.
  52395. If dontAddNonExistentFiles is true, then each file will be checked and only those
  52396. that exist will be added.
  52397. If filesToAvoid is non-zero, then it is considered to be a zero-terminated array of
  52398. pointers to file objects. Any files that appear in this list will not be added to the
  52399. menu - the reason for this is that you might have a number of files already open, so
  52400. might not want these to be shown in the menu.
  52401. It returns the number of items that were added.
  52402. */
  52403. int createPopupMenuItems (PopupMenu& menuToAddItemsTo,
  52404. int baseItemId,
  52405. bool showFullPaths,
  52406. bool dontAddNonExistentFiles,
  52407. const File** filesToAvoid = nullptr);
  52408. /** Returns a string that encapsulates all the files in the list.
  52409. The string that is returned can later be passed into restoreFromString() in
  52410. order to recreate the list. This is handy for persisting your list, e.g. in
  52411. a PropertiesFile object.
  52412. @see restoreFromString
  52413. */
  52414. String toString() const;
  52415. /** Restores the list from a previously stringified version of the list.
  52416. Pass in a stringified version created with toString() in order to persist/restore
  52417. your list.
  52418. @see toString
  52419. */
  52420. void restoreFromString (const String& stringifiedVersion);
  52421. private:
  52422. StringArray files;
  52423. int maxNumberOfItems;
  52424. JUCE_LEAK_DETECTOR (RecentlyOpenedFilesList);
  52425. };
  52426. #endif // __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  52427. /*** End of inlined file: juce_RecentlyOpenedFilesList.h ***/
  52428. #endif
  52429. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  52430. #endif
  52431. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  52432. /*** Start of inlined file: juce_SystemClipboard.h ***/
  52433. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  52434. #define __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  52435. /**
  52436. Handles reading/writing to the system's clipboard.
  52437. */
  52438. class JUCE_API SystemClipboard
  52439. {
  52440. public:
  52441. /** Copies a string of text onto the clipboard */
  52442. static void copyTextToClipboard (const String& text);
  52443. /** Gets the current clipboard's contents.
  52444. Obviously this might have come from another app, so could contain
  52445. anything..
  52446. */
  52447. static String getTextFromClipboard();
  52448. };
  52449. #endif // __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  52450. /*** End of inlined file: juce_SystemClipboard.h ***/
  52451. #endif
  52452. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  52453. #endif
  52454. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  52455. #endif
  52456. #ifndef __JUCE_UNITTEST_JUCEHEADER__
  52457. /*** Start of inlined file: juce_UnitTest.h ***/
  52458. #ifndef __JUCE_UNITTEST_JUCEHEADER__
  52459. #define __JUCE_UNITTEST_JUCEHEADER__
  52460. class UnitTestRunner;
  52461. /**
  52462. This is a base class for classes that perform a unit test.
  52463. To write a test using this class, your code should look something like this:
  52464. @code
  52465. class MyTest : public UnitTest
  52466. {
  52467. public:
  52468. MyTest() : UnitTest ("Foobar testing") {}
  52469. void runTest()
  52470. {
  52471. beginTest ("Part 1");
  52472. expect (myFoobar.doesSomething());
  52473. expect (myFoobar.doesSomethingElse());
  52474. beginTest ("Part 2");
  52475. expect (myOtherFoobar.doesSomething());
  52476. expect (myOtherFoobar.doesSomethingElse());
  52477. ...etc..
  52478. }
  52479. };
  52480. // Creating a static instance will automatically add the instance to the array
  52481. // returned by UnitTest::getAllTests(), so the test will be included when you call
  52482. // UnitTestRunner::runAllTests()
  52483. static MyTest test;
  52484. @endcode
  52485. To run a test, use the UnitTestRunner class.
  52486. @see UnitTestRunner
  52487. */
  52488. class JUCE_API UnitTest
  52489. {
  52490. public:
  52491. /** Creates a test with the given name. */
  52492. explicit UnitTest (const String& name);
  52493. /** Destructor. */
  52494. virtual ~UnitTest();
  52495. /** Returns the name of the test. */
  52496. const String& getName() const noexcept { return name; }
  52497. /** Runs the test, using the specified UnitTestRunner.
  52498. You shouldn't need to call this method directly - use
  52499. UnitTestRunner::runTests() instead.
  52500. */
  52501. void performTest (UnitTestRunner* runner);
  52502. /** Returns the set of all UnitTest objects that currently exist. */
  52503. static Array<UnitTest*>& getAllTests();
  52504. /** You can optionally implement this method to set up your test.
  52505. This method will be called before runTest().
  52506. */
  52507. virtual void initialise();
  52508. /** You can optionally implement this method to clear up after your test has been run.
  52509. This method will be called after runTest() has returned.
  52510. */
  52511. virtual void shutdown();
  52512. /** Implement this method in your subclass to actually run your tests.
  52513. The content of your implementation should call beginTest() and expect()
  52514. to perform the tests.
  52515. */
  52516. virtual void runTest() = 0;
  52517. /** Tells the system that a new subsection of tests is beginning.
  52518. This should be called from your runTest() method, and may be called
  52519. as many times as you like, to demarcate different sets of tests.
  52520. */
  52521. void beginTest (const String& testName);
  52522. /** Checks that the result of a test is true, and logs this result.
  52523. In your runTest() method, you should call this method for each condition that
  52524. you want to check, e.g.
  52525. @code
  52526. void runTest()
  52527. {
  52528. beginTest ("basic tests");
  52529. expect (x + y == 2);
  52530. expect (getThing() == someThing);
  52531. ...etc...
  52532. }
  52533. @endcode
  52534. If testResult is true, a pass is logged; if it's false, a failure is logged.
  52535. If the failure message is specified, it will be written to the log if the test fails.
  52536. */
  52537. void expect (bool testResult, const String& failureMessage = String::empty);
  52538. /** Compares two values, and if they don't match, prints out a message containing the
  52539. expected and actual result values.
  52540. */
  52541. template <class ValueType>
  52542. void expectEquals (ValueType actual, ValueType expected, String failureMessage = String::empty)
  52543. {
  52544. const bool result = (actual == expected);
  52545. if (! result)
  52546. {
  52547. if (failureMessage.isNotEmpty())
  52548. failureMessage << " -- ";
  52549. failureMessage << "Expected value: " << expected << ", Actual value: " << actual;
  52550. }
  52551. expect (result, failureMessage);
  52552. }
  52553. /** Writes a message to the test log.
  52554. This can only be called from within your runTest() method.
  52555. */
  52556. void logMessage (const String& message);
  52557. private:
  52558. const String name;
  52559. UnitTestRunner* runner;
  52560. JUCE_DECLARE_NON_COPYABLE (UnitTest);
  52561. };
  52562. /**
  52563. Runs a set of unit tests.
  52564. You can instantiate one of these objects and use it to invoke tests on a set of
  52565. UnitTest objects.
  52566. By using a subclass of UnitTestRunner, you can intercept logging messages and
  52567. perform custom behaviour when each test completes.
  52568. @see UnitTest
  52569. */
  52570. class JUCE_API UnitTestRunner
  52571. {
  52572. public:
  52573. /** */
  52574. UnitTestRunner();
  52575. /** Destructor. */
  52576. virtual ~UnitTestRunner();
  52577. /** Runs a set of tests.
  52578. The tests are performed in order, and the results are logged. To run all the
  52579. registered UnitTest objects that exist, use runAllTests().
  52580. */
  52581. void runTests (const Array<UnitTest*>& tests, bool assertOnFailure);
  52582. /** Runs all the UnitTest objects that currently exist.
  52583. This calls runTests() for all the objects listed in UnitTest::getAllTests().
  52584. */
  52585. void runAllTests (bool assertOnFailure);
  52586. /** Contains the results of a test.
  52587. One of these objects is instantiated each time UnitTest::beginTest() is called, and
  52588. it contains details of the number of subsequent UnitTest::expect() calls that are
  52589. made.
  52590. */
  52591. struct TestResult
  52592. {
  52593. /** The main name of this test (i.e. the name of the UnitTest object being run). */
  52594. String unitTestName;
  52595. /** The name of the current subcategory (i.e. the name that was set when UnitTest::beginTest() was called). */
  52596. String subcategoryName;
  52597. /** The number of UnitTest::expect() calls that succeeded. */
  52598. int passes;
  52599. /** The number of UnitTest::expect() calls that failed. */
  52600. int failures;
  52601. /** A list of messages describing the failed tests. */
  52602. StringArray messages;
  52603. };
  52604. /** Returns the number of TestResult objects that have been performed.
  52605. @see getResult
  52606. */
  52607. int getNumResults() const noexcept;
  52608. /** Returns one of the TestResult objects that describes a test that has been run.
  52609. @see getNumResults
  52610. */
  52611. const TestResult* getResult (int index) const noexcept;
  52612. protected:
  52613. /** Called when the list of results changes.
  52614. You can override this to perform some sort of behaviour when results are added.
  52615. */
  52616. virtual void resultsUpdated();
  52617. /** Logs a message about the current test progress.
  52618. By default this just writes the message to the Logger class, but you could override
  52619. this to do something else with the data.
  52620. */
  52621. virtual void logMessage (const String& message);
  52622. private:
  52623. friend class UnitTest;
  52624. UnitTest* currentTest;
  52625. String currentSubCategory;
  52626. OwnedArray <TestResult, CriticalSection> results;
  52627. bool assertOnFailure;
  52628. void beginNewTest (UnitTest* test, const String& subCategory);
  52629. void endTest();
  52630. void addPass();
  52631. void addFail (const String& failureMessage);
  52632. JUCE_DECLARE_NON_COPYABLE (UnitTestRunner);
  52633. };
  52634. #endif // __JUCE_UNITTEST_JUCEHEADER__
  52635. /*** End of inlined file: juce_UnitTest.h ***/
  52636. #endif
  52637. #ifndef __JUCE_WINDOWSREGISTRY_JUCEHEADER__
  52638. /*** Start of inlined file: juce_WindowsRegistry.h ***/
  52639. #ifndef __JUCE_WINDOWSREGISTRY_JUCEHEADER__
  52640. #define __JUCE_WINDOWSREGISTRY_JUCEHEADER__
  52641. #if JUCE_WINDOWS || DOXYGEN
  52642. /**
  52643. Contains some static helper functions for manipulating the MS Windows registry
  52644. (Only available on Windows, of course!)
  52645. */
  52646. class WindowsRegistry
  52647. {
  52648. /** Returns a string from the registry.
  52649. The path is a string for the entire path of a value in the registry,
  52650. e.g. "HKEY_CURRENT_USER\Software\foo\bar"
  52651. */
  52652. static String getValue (const String& regValuePath,
  52653. const String& defaultValue = String::empty);
  52654. /** Sets a registry value as a string.
  52655. This will take care of creating any groups needed to get to the given
  52656. registry value.
  52657. */
  52658. static void setValue (const String& regValuePath,
  52659. const String& value);
  52660. /** Returns true if the given value exists in the registry. */
  52661. static bool valueExists (const String& regValuePath);
  52662. /** Deletes a registry value. */
  52663. static void deleteValue (const String& regValuePath);
  52664. /** Deletes a registry key (which is registry-talk for 'folder'). */
  52665. static void deleteKey (const String& regKeyPath);
  52666. /** Creates a file association in the registry.
  52667. This lets you set the executable that should be launched by a given file extension.
  52668. @param fileExtension the file extension to associate, including the
  52669. initial dot, e.g. ".txt"
  52670. @param symbolicDescription a space-free short token to identify the file type
  52671. @param fullDescription a human-readable description of the file type
  52672. @param targetExecutable the executable that should be launched
  52673. @param iconResourceNumber the icon that gets displayed for the file type will be
  52674. found by looking up this resource number in the
  52675. executable. Pass 0 here to not use an icon
  52676. */
  52677. static void registerFileAssociation (const String& fileExtension,
  52678. const String& symbolicDescription,
  52679. const String& fullDescription,
  52680. const File& targetExecutable,
  52681. int iconResourceNumber);
  52682. private:
  52683. WindowsRegistry();
  52684. JUCE_DECLARE_NON_COPYABLE (WindowsRegistry);
  52685. };
  52686. #endif
  52687. #endif // __JUCE_WINDOWSREGISTRY_JUCEHEADER__
  52688. /*** End of inlined file: juce_WindowsRegistry.h ***/
  52689. #endif
  52690. #endif
  52691. /*** End of inlined file: juce_app_includes.h ***/
  52692. #endif
  52693. #if JUCE_MSVC
  52694. #pragma warning (pop)
  52695. #pragma pack (pop)
  52696. #endif
  52697. END_JUCE_NAMESPACE
  52698. #ifndef DONT_SET_USING_JUCE_NAMESPACE
  52699. #ifdef JUCE_NAMESPACE
  52700. // this will obviously save a lot of typing, but can be disabled by
  52701. // defining DONT_SET_USING_JUCE_NAMESPACE, in case there are conflicts.
  52702. using namespace JUCE_NAMESPACE;
  52703. /* On the Mac, these symbols are defined in the Mac libraries, so
  52704. these macros make it easier to reference them without writing out
  52705. the namespace every time.
  52706. If you run into difficulties where these macros interfere with the contents
  52707. of 3rd party header files, you may need to use the juce_WithoutMacros.h file - see
  52708. the comments in that file for more information.
  52709. */
  52710. #if (JUCE_MAC || JUCE_IOS) && ! JUCE_DONT_DEFINE_MACROS
  52711. #define Component JUCE_NAMESPACE::Component
  52712. #define MemoryBlock JUCE_NAMESPACE::MemoryBlock
  52713. #define Point JUCE_NAMESPACE::Point
  52714. #define Button JUCE_NAMESPACE::Button
  52715. #endif
  52716. /* "Rectangle" is defined in some of the newer windows header files, so this makes
  52717. it easier to use the juce version explicitly.
  52718. If you run into difficulties where this macro interferes with other 3rd party header
  52719. files, you may need to use the juce_WithoutMacros.h file - see the comments in that
  52720. file for more information.
  52721. */
  52722. #if JUCE_WINDOWS && ! JUCE_DONT_DEFINE_MACROS
  52723. #define Rectangle JUCE_NAMESPACE::Rectangle
  52724. #endif
  52725. #endif
  52726. #endif
  52727. /* Easy autolinking to the right JUCE libraries under win32.
  52728. Note that this can be disabled by defining DONT_AUTOLINK_TO_JUCE_LIBRARY before
  52729. including this header file.
  52730. */
  52731. #if JUCE_MSVC
  52732. #ifndef DONT_AUTOLINK_TO_JUCE_LIBRARY
  52733. /** If you want your application to link to Juce as a DLL instead of
  52734. a static library (on win32), just define the JUCE_DLL macro before
  52735. including juce.h
  52736. */
  52737. #ifdef JUCE_DLL
  52738. #if JUCE_DEBUG
  52739. #define AUTOLINKEDLIB "JUCE_debug.lib"
  52740. #else
  52741. #define AUTOLINKEDLIB "JUCE.lib"
  52742. #endif
  52743. #else
  52744. #if JUCE_DEBUG
  52745. #ifdef _WIN64
  52746. #define AUTOLINKEDLIB "jucelib_static_x64_debug.lib"
  52747. #else
  52748. #define AUTOLINKEDLIB "jucelib_static_Win32_debug.lib"
  52749. #endif
  52750. #else
  52751. #ifdef _WIN64
  52752. #define AUTOLINKEDLIB "jucelib_static_x64.lib"
  52753. #else
  52754. #define AUTOLINKEDLIB "jucelib_static_Win32.lib"
  52755. #endif
  52756. #endif
  52757. #endif
  52758. #pragma comment(lib, AUTOLINKEDLIB)
  52759. #if ! DONT_LIST_JUCE_AUTOLINKEDLIBS
  52760. #pragma message("JUCE! Library to link to: " AUTOLINKEDLIB)
  52761. #endif
  52762. // Auto-link the other win32 libs that are needed by library calls..
  52763. #if ! (defined (DONT_AUTOLINK_TO_WIN32_LIBRARIES) || defined (JUCE_DLL))
  52764. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  52765. // Auto-links to various win32 libs that are needed by library calls..
  52766. #pragma comment(lib, "kernel32.lib")
  52767. #pragma comment(lib, "user32.lib")
  52768. #pragma comment(lib, "shell32.lib")
  52769. #pragma comment(lib, "gdi32.lib")
  52770. #pragma comment(lib, "vfw32.lib")
  52771. #pragma comment(lib, "comdlg32.lib")
  52772. #pragma comment(lib, "winmm.lib")
  52773. #pragma comment(lib, "wininet.lib")
  52774. #pragma comment(lib, "ole32.lib")
  52775. #pragma comment(lib, "oleaut32.lib")
  52776. #pragma comment(lib, "advapi32.lib")
  52777. #pragma comment(lib, "ws2_32.lib")
  52778. #pragma comment(lib, "version.lib")
  52779. #pragma comment(lib, "shlwapi.lib")
  52780. #pragma comment(lib, "imm32.lib")
  52781. #ifdef _NATIVE_WCHAR_T_DEFINED
  52782. #ifdef _DEBUG
  52783. #pragma comment(lib, "comsuppwd.lib")
  52784. #else
  52785. #pragma comment(lib, "comsuppw.lib")
  52786. #endif
  52787. #else
  52788. #ifdef _DEBUG
  52789. #pragma comment(lib, "comsuppd.lib")
  52790. #else
  52791. #pragma comment(lib, "comsupp.lib")
  52792. #endif
  52793. #endif
  52794. #if JUCE_OPENGL
  52795. #pragma comment(lib, "OpenGL32.Lib")
  52796. #pragma comment(lib, "GlU32.Lib")
  52797. #endif
  52798. #if JUCE_QUICKTIME
  52799. #pragma comment (lib, "QTMLClient.lib")
  52800. #endif
  52801. #if JUCE_USE_CAMERA
  52802. #pragma comment (lib, "Strmiids.lib")
  52803. #pragma comment (lib, "wmvcore.lib")
  52804. #endif
  52805. #if JUCE_DIRECT2D
  52806. #pragma comment (lib, "Dwrite.lib")
  52807. #pragma comment (lib, "D2d1.lib")
  52808. #endif
  52809. #if JUCE_DIRECTSHOW
  52810. #pragma comment (lib, "strmiids.lib")
  52811. #endif
  52812. #if JUCE_MEDIAFOUNDATION
  52813. #pragma comment (lib, "mfuuid.lib")
  52814. #endif
  52815. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  52816. #endif
  52817. #endif
  52818. #endif
  52819. #endif // __JUCE_JUCEHEADER__
  52820. /*** End of inlined file: juce.h ***/
  52821. #endif // __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__