Audio plugin host https://kx.studio/carla
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.

721 lines
21KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. namespace FontValues
  18. {
  19. static float limitFontHeight (const float height) noexcept
  20. {
  21. return jlimit (0.1f, 10000.0f, height);
  22. }
  23. const float defaultFontHeight = 14.0f;
  24. String fallbackFont;
  25. String fallbackFontStyle;
  26. }
  27. typedef Typeface::Ptr (*GetTypefaceForFont) (const Font&);
  28. GetTypefaceForFont juce_getTypefaceForFont = nullptr;
  29. //==============================================================================
  30. class TypefaceCache : private DeletedAtShutdown
  31. {
  32. public:
  33. TypefaceCache() : counter (0)
  34. {
  35. setSize (10);
  36. }
  37. ~TypefaceCache()
  38. {
  39. clearSingletonInstance();
  40. }
  41. juce_DeclareSingleton (TypefaceCache, false);
  42. void setSize (const int numToCache)
  43. {
  44. const ScopedWriteLock sl (lock);
  45. faces.clear();
  46. faces.insertMultiple (-1, CachedFace(), numToCache);
  47. }
  48. void clear()
  49. {
  50. const ScopedWriteLock sl (lock);
  51. setSize (faces.size());
  52. defaultFace = nullptr;
  53. }
  54. Typeface::Ptr findTypefaceFor (const Font& font)
  55. {
  56. const ScopedReadLock slr (lock);
  57. const String faceName (font.getTypefaceName());
  58. const String faceStyle (font.getTypefaceStyle());
  59. jassert (faceName.isNotEmpty());
  60. for (int i = faces.size(); --i >= 0;)
  61. {
  62. CachedFace& face = faces.getReference(i);
  63. if (face.typefaceName == faceName
  64. && face.typefaceStyle == faceStyle
  65. && face.typeface != nullptr
  66. && face.typeface->isSuitableForFont (font))
  67. {
  68. face.lastUsageCount = ++counter;
  69. return face.typeface;
  70. }
  71. }
  72. const ScopedWriteLock slw (lock);
  73. int replaceIndex = 0;
  74. size_t bestLastUsageCount = std::numeric_limits<size_t>::max();
  75. for (int i = faces.size(); --i >= 0;)
  76. {
  77. const size_t lu = faces.getReference(i).lastUsageCount;
  78. if (bestLastUsageCount > lu)
  79. {
  80. bestLastUsageCount = lu;
  81. replaceIndex = i;
  82. }
  83. }
  84. CachedFace& face = faces.getReference (replaceIndex);
  85. face.typefaceName = faceName;
  86. face.typefaceStyle = faceStyle;
  87. face.lastUsageCount = ++counter;
  88. if (juce_getTypefaceForFont == nullptr)
  89. face.typeface = Font::getDefaultTypefaceForFont (font);
  90. else
  91. face.typeface = juce_getTypefaceForFont (font);
  92. jassert (face.typeface != nullptr); // the look and feel must return a typeface!
  93. if (defaultFace == nullptr && font == Font())
  94. defaultFace = face.typeface;
  95. return face.typeface;
  96. }
  97. Typeface::Ptr defaultFace;
  98. private:
  99. struct CachedFace
  100. {
  101. CachedFace() noexcept : lastUsageCount (0) {}
  102. // Although it seems a bit wacky to store the name here, it's because it may be a
  103. // placeholder rather than a real one, e.g. "<Sans-Serif>" vs the actual typeface name.
  104. // Since the typeface itself doesn't know that it may have this alias, the name under
  105. // which it was fetched needs to be stored separately.
  106. String typefaceName, typefaceStyle;
  107. size_t lastUsageCount;
  108. Typeface::Ptr typeface;
  109. };
  110. ReadWriteLock lock;
  111. Array<CachedFace> faces;
  112. size_t counter;
  113. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TypefaceCache)
  114. };
  115. juce_ImplementSingleton (TypefaceCache)
  116. void Typeface::setTypefaceCacheSize (int numFontsToCache)
  117. {
  118. TypefaceCache::getInstance()->setSize (numFontsToCache);
  119. }
  120. #if JUCE_MODULE_AVAILABLE_juce_opengl
  121. extern void clearOpenGLGlyphCache();
  122. #endif
  123. void Typeface::clearTypefaceCache()
  124. {
  125. TypefaceCache::getInstance()->clear();
  126. RenderingHelpers::SoftwareRendererSavedState::clearGlyphCache();
  127. #if JUCE_MODULE_AVAILABLE_juce_opengl
  128. clearOpenGLGlyphCache();
  129. #endif
  130. }
  131. //==============================================================================
  132. class Font::SharedFontInternal : public ReferenceCountedObject
  133. {
  134. public:
  135. SharedFontInternal() noexcept
  136. : typeface (TypefaceCache::getInstance()->defaultFace),
  137. typefaceName (Font::getDefaultSansSerifFontName()),
  138. typefaceStyle (Font::getDefaultStyle()),
  139. height (FontValues::defaultFontHeight),
  140. horizontalScale (1.0f), kerning (0), ascent (0), underline (false)
  141. {
  142. }
  143. SharedFontInternal (int styleFlags, float fontHeight) noexcept
  144. : typefaceName (Font::getDefaultSansSerifFontName()),
  145. typefaceStyle (FontStyleHelpers::getStyleName (styleFlags)),
  146. height (fontHeight),
  147. horizontalScale (1.0f), kerning (0), ascent (0), underline ((styleFlags & underlined) != 0)
  148. {
  149. if (styleFlags == plain)
  150. typeface = TypefaceCache::getInstance()->defaultFace;
  151. }
  152. SharedFontInternal (const String& name, int styleFlags, float fontHeight) noexcept
  153. : typefaceName (name),
  154. typefaceStyle (FontStyleHelpers::getStyleName (styleFlags)),
  155. height (fontHeight),
  156. horizontalScale (1.0f), kerning (0), ascent (0), underline ((styleFlags & underlined) != 0)
  157. {
  158. if (styleFlags == plain && typefaceName.isEmpty())
  159. typeface = TypefaceCache::getInstance()->defaultFace;
  160. }
  161. SharedFontInternal (const String& name, const String& style, float fontHeight) noexcept
  162. : typefaceName (name), typefaceStyle (style), height (fontHeight),
  163. horizontalScale (1.0f), kerning (0), ascent (0), underline (false)
  164. {
  165. if (typefaceName.isEmpty())
  166. typefaceName = Font::getDefaultSansSerifFontName();
  167. }
  168. explicit SharedFontInternal (const Typeface::Ptr& face) noexcept
  169. : typeface (face),
  170. typefaceName (face->getName()),
  171. typefaceStyle (face->getStyle()),
  172. height (FontValues::defaultFontHeight),
  173. horizontalScale (1.0f), kerning (0), ascent (0), underline (false)
  174. {
  175. jassert (typefaceName.isNotEmpty());
  176. }
  177. SharedFontInternal (const SharedFontInternal& other) noexcept
  178. : ReferenceCountedObject(),
  179. typeface (other.typeface),
  180. typefaceName (other.typefaceName),
  181. typefaceStyle (other.typefaceStyle),
  182. height (other.height),
  183. horizontalScale (other.horizontalScale),
  184. kerning (other.kerning),
  185. ascent (other.ascent),
  186. underline (other.underline)
  187. {
  188. }
  189. bool operator== (const SharedFontInternal& other) const noexcept
  190. {
  191. return height == other.height
  192. && underline == other.underline
  193. && horizontalScale == other.horizontalScale
  194. && kerning == other.kerning
  195. && typefaceName == other.typefaceName
  196. && typefaceStyle == other.typefaceStyle;
  197. }
  198. Typeface::Ptr typeface;
  199. String typefaceName, typefaceStyle;
  200. float height, horizontalScale, kerning, ascent;
  201. bool underline;
  202. };
  203. //==============================================================================
  204. Font::Font() : font (new SharedFontInternal()) {}
  205. Font::Font (const Typeface::Ptr& typeface) : font (new SharedFontInternal (typeface)) {}
  206. Font::Font (const Font& other) noexcept : font (other.font) {}
  207. Font::Font (float fontHeight, int styleFlags)
  208. : font (new SharedFontInternal (styleFlags, FontValues::limitFontHeight (fontHeight)))
  209. {
  210. }
  211. Font::Font (const String& typefaceName, float fontHeight, int styleFlags)
  212. : font (new SharedFontInternal (typefaceName, styleFlags, FontValues::limitFontHeight (fontHeight)))
  213. {
  214. }
  215. Font::Font (const String& typefaceName, const String& typefaceStyle, float fontHeight)
  216. : font (new SharedFontInternal (typefaceName, typefaceStyle, FontValues::limitFontHeight (fontHeight)))
  217. {
  218. }
  219. Font& Font::operator= (const Font& other) noexcept
  220. {
  221. font = other.font;
  222. return *this;
  223. }
  224. #if JUCE_COMPILER_SUPPORTS_MOVE_SEMANTICS
  225. Font::Font (Font&& other) noexcept
  226. : font (static_cast<ReferenceCountedObjectPtr<SharedFontInternal>&&> (other.font))
  227. {
  228. }
  229. Font& Font::operator= (Font&& other) noexcept
  230. {
  231. font = static_cast<ReferenceCountedObjectPtr<SharedFontInternal>&&> (other.font);
  232. return *this;
  233. }
  234. #endif
  235. Font::~Font() noexcept
  236. {
  237. }
  238. bool Font::operator== (const Font& other) const noexcept
  239. {
  240. return font == other.font
  241. || *font == *other.font;
  242. }
  243. bool Font::operator!= (const Font& other) const noexcept
  244. {
  245. return ! operator== (other);
  246. }
  247. void Font::dupeInternalIfShared()
  248. {
  249. if (font->getReferenceCount() > 1)
  250. font = new SharedFontInternal (*font);
  251. }
  252. void Font::checkTypefaceSuitability()
  253. {
  254. if (font->typeface != nullptr && ! font->typeface->isSuitableForFont (*this))
  255. font->typeface = nullptr;
  256. }
  257. //==============================================================================
  258. struct FontPlaceholderNames
  259. {
  260. FontPlaceholderNames()
  261. : sans ("<Sans-Serif>"),
  262. serif ("<Serif>"),
  263. mono ("<Monospaced>"),
  264. regular ("<Regular>")
  265. {
  266. }
  267. String sans, serif, mono, regular;
  268. };
  269. const FontPlaceholderNames& getFontPlaceholderNames()
  270. {
  271. static FontPlaceholderNames names;
  272. return names;
  273. }
  274. #if JUCE_MSVC
  275. // This is a workaround for the lack of thread-safety in MSVC's handling of function-local
  276. // statics - if multiple threads all try to create the first Font object at the same time,
  277. // it can cause a race-condition in creating these placeholder strings.
  278. struct FontNamePreloader { FontNamePreloader() { getFontPlaceholderNames(); } };
  279. static FontNamePreloader fnp;
  280. #endif
  281. const String& Font::getDefaultSansSerifFontName() { return getFontPlaceholderNames().sans; }
  282. const String& Font::getDefaultSerifFontName() { return getFontPlaceholderNames().serif; }
  283. const String& Font::getDefaultMonospacedFontName() { return getFontPlaceholderNames().mono; }
  284. const String& Font::getDefaultStyle() { return getFontPlaceholderNames().regular; }
  285. const String& Font::getTypefaceName() const noexcept { return font->typefaceName; }
  286. const String& Font::getTypefaceStyle() const noexcept { return font->typefaceStyle; }
  287. void Font::setTypefaceName (const String& faceName)
  288. {
  289. if (faceName != font->typefaceName)
  290. {
  291. jassert (faceName.isNotEmpty());
  292. dupeInternalIfShared();
  293. font->typefaceName = faceName;
  294. font->typeface = nullptr;
  295. font->ascent = 0;
  296. }
  297. }
  298. void Font::setTypefaceStyle (const String& typefaceStyle)
  299. {
  300. if (typefaceStyle != font->typefaceStyle)
  301. {
  302. dupeInternalIfShared();
  303. font->typefaceStyle = typefaceStyle;
  304. font->typeface = nullptr;
  305. font->ascent = 0;
  306. }
  307. }
  308. Font Font::withTypefaceStyle (const String& newStyle) const
  309. {
  310. Font f (*this);
  311. f.setTypefaceStyle (newStyle);
  312. return f;
  313. }
  314. StringArray Font::getAvailableStyles() const
  315. {
  316. return findAllTypefaceStyles (getTypeface()->getName());
  317. }
  318. Typeface* Font::getTypeface() const
  319. {
  320. if (font->typeface == nullptr)
  321. {
  322. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  323. jassert (font->typeface != nullptr);
  324. }
  325. return font->typeface;
  326. }
  327. //==============================================================================
  328. const String& Font::getFallbackFontName()
  329. {
  330. return FontValues::fallbackFont;
  331. }
  332. void Font::setFallbackFontName (const String& name)
  333. {
  334. FontValues::fallbackFont = name;
  335. #if JUCE_MAC || JUCE_IOS
  336. jassertfalse; // Note that use of a fallback font isn't currently implemented in OSX..
  337. #endif
  338. }
  339. const String& Font::getFallbackFontStyle()
  340. {
  341. return FontValues::fallbackFontStyle;
  342. }
  343. void Font::setFallbackFontStyle (const String& style)
  344. {
  345. FontValues::fallbackFontStyle = style;
  346. #if JUCE_MAC || JUCE_IOS
  347. jassertfalse; // Note that use of a fallback font isn't currently implemented in OSX..
  348. #endif
  349. }
  350. //==============================================================================
  351. Font Font::withHeight (const float newHeight) const
  352. {
  353. Font f (*this);
  354. f.setHeight (newHeight);
  355. return f;
  356. }
  357. float Font::getHeightToPointsFactor() const
  358. {
  359. return getTypeface()->getHeightToPointsFactor();
  360. }
  361. Font Font::withPointHeight (float heightInPoints) const
  362. {
  363. Font f (*this);
  364. f.setHeight (heightInPoints / getHeightToPointsFactor());
  365. return f;
  366. }
  367. void Font::setHeight (float newHeight)
  368. {
  369. newHeight = FontValues::limitFontHeight (newHeight);
  370. if (font->height != newHeight)
  371. {
  372. dupeInternalIfShared();
  373. font->height = newHeight;
  374. checkTypefaceSuitability();
  375. }
  376. }
  377. void Font::setHeightWithoutChangingWidth (float newHeight)
  378. {
  379. newHeight = FontValues::limitFontHeight (newHeight);
  380. if (font->height != newHeight)
  381. {
  382. dupeInternalIfShared();
  383. font->horizontalScale *= (font->height / newHeight);
  384. font->height = newHeight;
  385. checkTypefaceSuitability();
  386. }
  387. }
  388. int Font::getStyleFlags() const noexcept
  389. {
  390. int styleFlags = font->underline ? underlined : plain;
  391. if (isBold()) styleFlags |= bold;
  392. if (isItalic()) styleFlags |= italic;
  393. return styleFlags;
  394. }
  395. Font Font::withStyle (const int newFlags) const
  396. {
  397. Font f (*this);
  398. f.setStyleFlags (newFlags);
  399. return f;
  400. }
  401. void Font::setStyleFlags (const int newFlags)
  402. {
  403. if (getStyleFlags() != newFlags)
  404. {
  405. dupeInternalIfShared();
  406. font->typeface = nullptr;
  407. font->typefaceStyle = FontStyleHelpers::getStyleName (newFlags);
  408. font->underline = (newFlags & underlined) != 0;
  409. font->ascent = 0;
  410. }
  411. }
  412. void Font::setSizeAndStyle (float newHeight,
  413. const int newStyleFlags,
  414. const float newHorizontalScale,
  415. const float newKerningAmount)
  416. {
  417. newHeight = FontValues::limitFontHeight (newHeight);
  418. if (font->height != newHeight
  419. || font->horizontalScale != newHorizontalScale
  420. || font->kerning != newKerningAmount)
  421. {
  422. dupeInternalIfShared();
  423. font->height = newHeight;
  424. font->horizontalScale = newHorizontalScale;
  425. font->kerning = newKerningAmount;
  426. checkTypefaceSuitability();
  427. }
  428. setStyleFlags (newStyleFlags);
  429. }
  430. void Font::setSizeAndStyle (float newHeight,
  431. const String& newStyle,
  432. const float newHorizontalScale,
  433. const float newKerningAmount)
  434. {
  435. newHeight = FontValues::limitFontHeight (newHeight);
  436. if (font->height != newHeight
  437. || font->horizontalScale != newHorizontalScale
  438. || font->kerning != newKerningAmount)
  439. {
  440. dupeInternalIfShared();
  441. font->height = newHeight;
  442. font->horizontalScale = newHorizontalScale;
  443. font->kerning = newKerningAmount;
  444. checkTypefaceSuitability();
  445. }
  446. setTypefaceStyle (newStyle);
  447. }
  448. Font Font::withHorizontalScale (const float newHorizontalScale) const
  449. {
  450. Font f (*this);
  451. f.setHorizontalScale (newHorizontalScale);
  452. return f;
  453. }
  454. void Font::setHorizontalScale (const float scaleFactor)
  455. {
  456. dupeInternalIfShared();
  457. font->horizontalScale = scaleFactor;
  458. checkTypefaceSuitability();
  459. }
  460. float Font::getHorizontalScale() const noexcept
  461. {
  462. return font->horizontalScale;
  463. }
  464. float Font::getExtraKerningFactor() const noexcept
  465. {
  466. return font->kerning;
  467. }
  468. Font Font::withExtraKerningFactor (const float extraKerning) const
  469. {
  470. Font f (*this);
  471. f.setExtraKerningFactor (extraKerning);
  472. return f;
  473. }
  474. void Font::setExtraKerningFactor (const float extraKerning)
  475. {
  476. dupeInternalIfShared();
  477. font->kerning = extraKerning;
  478. checkTypefaceSuitability();
  479. }
  480. Font Font::boldened() const { return withStyle (getStyleFlags() | bold); }
  481. Font Font::italicised() const { return withStyle (getStyleFlags() | italic); }
  482. bool Font::isBold() const noexcept { return FontStyleHelpers::isBold (font->typefaceStyle); }
  483. bool Font::isItalic() const noexcept { return FontStyleHelpers::isItalic (font->typefaceStyle); }
  484. bool Font::isUnderlined() const noexcept { return font->underline; }
  485. void Font::setBold (const bool shouldBeBold)
  486. {
  487. const int flags = getStyleFlags();
  488. setStyleFlags (shouldBeBold ? (flags | bold)
  489. : (flags & ~bold));
  490. }
  491. void Font::setItalic (const bool shouldBeItalic)
  492. {
  493. const int flags = getStyleFlags();
  494. setStyleFlags (shouldBeItalic ? (flags | italic)
  495. : (flags & ~italic));
  496. }
  497. void Font::setUnderline (const bool shouldBeUnderlined)
  498. {
  499. dupeInternalIfShared();
  500. font->underline = shouldBeUnderlined;
  501. checkTypefaceSuitability();
  502. }
  503. float Font::getAscent() const
  504. {
  505. if (font->ascent == 0)
  506. font->ascent = getTypeface()->getAscent();
  507. return font->height * font->ascent;
  508. }
  509. float Font::getHeight() const noexcept { return font->height; }
  510. float Font::getDescent() const { return font->height - getAscent(); }
  511. float Font::getHeightInPoints() const { return getHeight() * getHeightToPointsFactor(); }
  512. float Font::getAscentInPoints() const { return getAscent() * getHeightToPointsFactor(); }
  513. float Font::getDescentInPoints() const { return getDescent() * getHeightToPointsFactor(); }
  514. int Font::getStringWidth (const String& text) const
  515. {
  516. return roundToInt (getStringWidthFloat (text));
  517. }
  518. float Font::getStringWidthFloat (const String& text) const
  519. {
  520. float w = getTypeface()->getStringWidth (text);
  521. if (font->kerning != 0)
  522. w += font->kerning * text.length();
  523. return w * font->height * font->horizontalScale;
  524. }
  525. void Font::getGlyphPositions (const String& text, Array<int>& glyphs, Array<float>& xOffsets) const
  526. {
  527. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  528. const int num = xOffsets.size();
  529. if (num > 0)
  530. {
  531. const float scale = font->height * font->horizontalScale;
  532. float* const x = xOffsets.getRawDataPointer();
  533. if (font->kerning != 0)
  534. {
  535. for (int i = 0; i < num; ++i)
  536. x[i] = (x[i] + i * font->kerning) * scale;
  537. }
  538. else
  539. {
  540. for (int i = 0; i < num; ++i)
  541. x[i] *= scale;
  542. }
  543. }
  544. }
  545. void Font::findFonts (Array<Font>& destArray)
  546. {
  547. const StringArray names (findAllTypefaceNames());
  548. for (int i = 0; i < names.size(); ++i)
  549. {
  550. const StringArray styles (findAllTypefaceStyles (names[i]));
  551. String style ("Regular");
  552. if (! styles.contains (style, true))
  553. style = styles[0];
  554. destArray.add (Font (names[i], style, FontValues::defaultFontHeight));
  555. }
  556. }
  557. //==============================================================================
  558. String Font::toString() const
  559. {
  560. String s;
  561. if (getTypefaceName() != getDefaultSansSerifFontName())
  562. s << getTypefaceName() << "; ";
  563. s << String (getHeight(), 1);
  564. if (getTypefaceStyle() != getDefaultStyle())
  565. s << ' ' << getTypefaceStyle();
  566. return s;
  567. }
  568. Font Font::fromString (const String& fontDescription)
  569. {
  570. const int separator = fontDescription.indexOfChar (';');
  571. String name;
  572. if (separator > 0)
  573. name = fontDescription.substring (0, separator).trim();
  574. if (name.isEmpty())
  575. name = getDefaultSansSerifFontName();
  576. String sizeAndStyle (fontDescription.substring (separator + 1).trimStart());
  577. float height = sizeAndStyle.getFloatValue();
  578. if (height <= 0)
  579. height = 10.0f;
  580. const String style (sizeAndStyle.fromFirstOccurrenceOf (" ", false, false));
  581. return Font (name, style, height);
  582. }