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.

1306 lines
49KB

  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. #if (! defined (JUCE_CORETEXT_AVAILABLE)) \
  18. && (JUCE_IOS || (JUCE_MAC && MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4))
  19. #define JUCE_CORETEXT_AVAILABLE 1
  20. #endif
  21. const float referenceFontSize = 1024.0f;
  22. #if JUCE_CORETEXT_AVAILABLE
  23. #if JUCE_MAC && MAC_OS_X_VERSION_MAX_ALLOWED == MAC_OS_X_VERSION_10_5
  24. extern "C"
  25. {
  26. void CTRunGetAdvances (CTRunRef, CFRange, CGSize buffer[]);
  27. const CGSize* CTRunGetAdvancesPtr (CTRunRef);
  28. }
  29. #endif
  30. static CTFontRef getCTFontFromTypeface (const Font& f);
  31. namespace CoreTextTypeLayout
  32. {
  33. static String findBestAvailableStyle (const Font& font, CGAffineTransform& requiredTransform)
  34. {
  35. const StringArray availableStyles (Font::findAllTypefaceStyles (font.getTypefaceName()));
  36. const String style (font.getTypefaceStyle());
  37. if (! availableStyles.contains (style))
  38. {
  39. if (font.isItalic()) // Fake-up an italic font if there isn't a real one.
  40. requiredTransform = CGAffineTransformMake (1.0f, 0, 0.25f, 1.0f, 0, 0);
  41. return availableStyles[0];
  42. }
  43. return style;
  44. }
  45. // Workaround for Apple bug in CTFontCreateWithFontDescriptor in Garageband/Logic on 10.6
  46. #if JUCE_MAC && ((! defined (MAC_OS_X_VERSION_10_7)) || MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_7)
  47. static CTFontRef getFontWithTrait (CTFontRef ctFontRef, CTFontSymbolicTraits trait)
  48. {
  49. if (CTFontRef newFont = CTFontCreateCopyWithSymbolicTraits (ctFontRef, 0.0f, nullptr, trait, trait))
  50. {
  51. CFRelease (ctFontRef);
  52. return newFont;
  53. }
  54. return ctFontRef;
  55. }
  56. static CTFontRef useStyleFallbackIfNecessary (CTFontRef ctFontRef, CFStringRef cfFontFamily,
  57. const float fontSizePoints, const Font& font)
  58. {
  59. CFStringRef cfActualFontFamily = (CFStringRef) CTFontCopyAttribute (ctFontRef, kCTFontFamilyNameAttribute);
  60. if (CFStringCompare (cfFontFamily, cfActualFontFamily, 0) != kCFCompareEqualTo)
  61. {
  62. CFRelease (ctFontRef);
  63. ctFontRef = CTFontCreateWithName (cfFontFamily, fontSizePoints, nullptr);
  64. if (font.isItalic()) ctFontRef = getFontWithTrait (ctFontRef, kCTFontItalicTrait);
  65. if (font.isBold()) ctFontRef = getFontWithTrait (ctFontRef, kCTFontBoldTrait);
  66. }
  67. CFRelease (cfActualFontFamily);
  68. return ctFontRef;
  69. }
  70. #endif
  71. static float getFontTotalHeight (CTFontRef font)
  72. {
  73. return std::abs ((float) CTFontGetAscent (font)) + std::abs ((float) CTFontGetDescent (font));
  74. }
  75. static float getHeightToPointsFactor (CTFontRef font)
  76. {
  77. return referenceFontSize / getFontTotalHeight (font);
  78. }
  79. static CTFontRef getFontWithPointSize (CTFontRef font, float size)
  80. {
  81. CTFontRef newFont = CTFontCreateCopyWithAttributes (font, size, nullptr, nullptr);
  82. CFRelease (font);
  83. return newFont;
  84. }
  85. static CTFontRef createCTFont (const Font& font, const float fontSizePoints, CGAffineTransform& transformRequired)
  86. {
  87. CFStringRef cfFontFamily = FontStyleHelpers::getConcreteFamilyName (font).toCFString();
  88. CFStringRef cfFontStyle = findBestAvailableStyle (font, transformRequired).toCFString();
  89. CFStringRef keys[] = { kCTFontFamilyNameAttribute, kCTFontStyleNameAttribute };
  90. CFTypeRef values[] = { cfFontFamily, cfFontStyle };
  91. CFDictionaryRef fontDescAttributes = CFDictionaryCreate (nullptr, (const void**) &keys,
  92. (const void**) &values,
  93. numElementsInArray (keys),
  94. &kCFTypeDictionaryKeyCallBacks,
  95. &kCFTypeDictionaryValueCallBacks);
  96. CFRelease (cfFontStyle);
  97. CTFontDescriptorRef ctFontDescRef = CTFontDescriptorCreateWithAttributes (fontDescAttributes);
  98. CFRelease (fontDescAttributes);
  99. CTFontRef ctFontRef = CTFontCreateWithFontDescriptor (ctFontDescRef, fontSizePoints, nullptr);
  100. CFRelease (ctFontDescRef);
  101. #if JUCE_MAC && ((! defined (MAC_OS_X_VERSION_10_7)) || MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_7)
  102. ctFontRef = useStyleFallbackIfNecessary (ctFontRef, cfFontFamily, fontSizePoints, font);
  103. #endif
  104. CFRelease (cfFontFamily);
  105. return ctFontRef;
  106. }
  107. //==============================================================================
  108. struct Advances
  109. {
  110. Advances (CTRunRef run, const CFIndex numGlyphs)
  111. : advances (CTRunGetAdvancesPtr (run))
  112. {
  113. if (advances == nullptr)
  114. {
  115. local.malloc ((size_t) numGlyphs);
  116. CTRunGetAdvances (run, CFRangeMake (0, 0), local);
  117. advances = local;
  118. }
  119. }
  120. const CGSize* advances;
  121. HeapBlock<CGSize> local;
  122. };
  123. struct Glyphs
  124. {
  125. Glyphs (CTRunRef run, const size_t numGlyphs)
  126. : glyphs (CTRunGetGlyphsPtr (run))
  127. {
  128. if (glyphs == nullptr)
  129. {
  130. local.malloc (numGlyphs);
  131. CTRunGetGlyphs (run, CFRangeMake (0, 0), local);
  132. glyphs = local;
  133. }
  134. }
  135. const CGGlyph* glyphs;
  136. HeapBlock<CGGlyph> local;
  137. };
  138. struct Positions
  139. {
  140. Positions (CTRunRef run, const size_t numGlyphs)
  141. : points (CTRunGetPositionsPtr (run))
  142. {
  143. if (points == nullptr)
  144. {
  145. local.malloc (numGlyphs);
  146. CTRunGetPositions (run, CFRangeMake (0, 0), local);
  147. points = local;
  148. }
  149. }
  150. const CGPoint* points;
  151. HeapBlock<CGPoint> local;
  152. };
  153. struct LineInfo
  154. {
  155. LineInfo (CTFrameRef frame, CTLineRef line, CFIndex lineIndex)
  156. {
  157. CTFrameGetLineOrigins (frame, CFRangeMake (lineIndex, 1), &origin);
  158. CTLineGetTypographicBounds (line, &ascent, &descent, &leading);
  159. }
  160. CGPoint origin;
  161. CGFloat ascent, descent, leading;
  162. };
  163. static CTFontRef getOrCreateFont (const Font& f)
  164. {
  165. if (CTFontRef ctf = getCTFontFromTypeface (f))
  166. {
  167. CFRetain (ctf);
  168. return ctf;
  169. }
  170. CGAffineTransform transform;
  171. return createCTFont (f, referenceFontSize, transform);
  172. }
  173. //==============================================================================
  174. static CFAttributedStringRef createCFAttributedString (const AttributedString& text)
  175. {
  176. #if JUCE_IOS
  177. CGColorSpaceRef rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  178. #endif
  179. CFStringRef cfText = text.getText().toCFString();
  180. CFMutableAttributedStringRef attribString = CFAttributedStringCreateMutable (kCFAllocatorDefault, 0);
  181. CFAttributedStringReplaceString (attribString, CFRangeMake(0, 0), cfText);
  182. CFRelease (cfText);
  183. const int numCharacterAttributes = text.getNumAttributes();
  184. for (int i = 0; i < numCharacterAttributes; ++i)
  185. {
  186. const AttributedString::Attribute& attr = *text.getAttribute (i);
  187. if (attr.range.getStart() > CFAttributedStringGetLength (attribString))
  188. continue;
  189. Range<int> range (attr.range);
  190. range.setEnd (jmin (range.getEnd(), (int) CFAttributedStringGetLength (attribString)));
  191. if (const Font* const f = attr.getFont())
  192. {
  193. if (CTFontRef ctFontRef = getOrCreateFont (*f))
  194. {
  195. ctFontRef = getFontWithPointSize (ctFontRef, f->getHeight() * getHeightToPointsFactor (ctFontRef));
  196. CFAttributedStringSetAttribute (attribString, CFRangeMake (range.getStart(), range.getLength()),
  197. kCTFontAttributeName, ctFontRef);
  198. CFRelease (ctFontRef);
  199. }
  200. }
  201. if (const Colour* const col = attr.getColour())
  202. {
  203. #if JUCE_IOS
  204. const CGFloat components[] = { col->getFloatRed(),
  205. col->getFloatGreen(),
  206. col->getFloatBlue(),
  207. col->getFloatAlpha() };
  208. CGColorRef colour = CGColorCreate (rgbColourSpace, components);
  209. #else
  210. CGColorRef colour = CGColorCreateGenericRGB (col->getFloatRed(),
  211. col->getFloatGreen(),
  212. col->getFloatBlue(),
  213. col->getFloatAlpha());
  214. #endif
  215. CFAttributedStringSetAttribute (attribString,
  216. CFRangeMake (range.getStart(), range.getLength()),
  217. kCTForegroundColorAttributeName, colour);
  218. CGColorRelease (colour);
  219. }
  220. }
  221. // Paragraph Attributes
  222. CTTextAlignment ctTextAlignment = kCTLeftTextAlignment;
  223. CTLineBreakMode ctLineBreakMode = kCTLineBreakByWordWrapping;
  224. const CGFloat ctLineSpacing = text.getLineSpacing();
  225. switch (text.getJustification().getOnlyHorizontalFlags())
  226. {
  227. case Justification::left: break;
  228. case Justification::right: ctTextAlignment = kCTRightTextAlignment; break;
  229. case Justification::horizontallyCentred: ctTextAlignment = kCTCenterTextAlignment; break;
  230. case Justification::horizontallyJustified: ctTextAlignment = kCTJustifiedTextAlignment; break;
  231. default: jassertfalse; break; // Illegal justification flags
  232. }
  233. switch (text.getWordWrap())
  234. {
  235. case AttributedString::byWord: break;
  236. case AttributedString::none: ctLineBreakMode = kCTLineBreakByClipping; break;
  237. case AttributedString::byChar: ctLineBreakMode = kCTLineBreakByCharWrapping; break;
  238. default: break;
  239. }
  240. CTParagraphStyleSetting settings[] =
  241. {
  242. { kCTParagraphStyleSpecifierAlignment, sizeof (CTTextAlignment), &ctTextAlignment },
  243. { kCTParagraphStyleSpecifierLineBreakMode, sizeof (CTLineBreakMode), &ctLineBreakMode },
  244. #if defined (MAC_OS_X_VERSION_10_7) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
  245. { kCTParagraphStyleSpecifierLineSpacingAdjustment, sizeof (CGFloat), &ctLineSpacing }
  246. #else
  247. { kCTParagraphStyleSpecifierLineSpacing, sizeof (CGFloat), &ctLineSpacing }
  248. #endif
  249. };
  250. CTParagraphStyleRef ctParagraphStyleRef = CTParagraphStyleCreate (settings, (size_t) numElementsInArray (settings));
  251. CFAttributedStringSetAttribute (attribString, CFRangeMake (0, CFAttributedStringGetLength (attribString)),
  252. kCTParagraphStyleAttributeName, ctParagraphStyleRef);
  253. CFRelease (ctParagraphStyleRef);
  254. #if JUCE_IOS
  255. CGColorSpaceRelease (rgbColourSpace);
  256. #endif
  257. return attribString;
  258. }
  259. static CTFrameRef createCTFrame (const AttributedString& text, CGRect bounds)
  260. {
  261. CFAttributedStringRef attribString = createCFAttributedString (text);
  262. CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString (attribString);
  263. CFRelease (attribString);
  264. CGMutablePathRef path = CGPathCreateMutable();
  265. CGPathAddRect (path, nullptr, bounds);
  266. CTFrameRef frame = CTFramesetterCreateFrame (framesetter, CFRangeMake (0, 0), path, nullptr);
  267. CFRelease (framesetter);
  268. CGPathRelease (path);
  269. return frame;
  270. }
  271. static Range<float> getLineVerticalRange (CTFrameRef frame, CFArrayRef lines, int lineIndex)
  272. {
  273. LineInfo info (frame, (CTLineRef) CFArrayGetValueAtIndex (lines, lineIndex), lineIndex);
  274. return Range<float> ((float) (info.origin.y - info.descent),
  275. (float) (info.origin.y + info.ascent));
  276. }
  277. static float findCTFrameHeight (CTFrameRef frame)
  278. {
  279. CFArrayRef lines = CTFrameGetLines (frame);
  280. const CFIndex numLines = CFArrayGetCount (lines);
  281. if (numLines == 0)
  282. return 0;
  283. Range<float> range (getLineVerticalRange (frame, lines, 0));
  284. if (numLines > 1)
  285. range = range.getUnionWith (getLineVerticalRange (frame, lines, (int) numLines - 1));
  286. return range.getLength();
  287. }
  288. static void drawToCGContext (const AttributedString& text, const Rectangle<float>& area,
  289. const CGContextRef& context, const float flipHeight)
  290. {
  291. CTFrameRef frame = createCTFrame (text, CGRectMake ((CGFloat) area.getX(), flipHeight - (CGFloat) area.getBottom(),
  292. (CGFloat) area.getWidth(), (CGFloat) area.getHeight()));
  293. const int verticalJustification = text.getJustification().getOnlyVerticalFlags();
  294. if (verticalJustification == Justification::verticallyCentred
  295. || verticalJustification == Justification::bottom)
  296. {
  297. float adjust = area.getHeight() - findCTFrameHeight (frame);
  298. if (verticalJustification == Justification::verticallyCentred)
  299. adjust *= 0.5f;
  300. CGContextSaveGState (context);
  301. CGContextTranslateCTM (context, 0, -adjust);
  302. CTFrameDraw (frame, context);
  303. CGContextRestoreGState (context);
  304. }
  305. else
  306. {
  307. CTFrameDraw (frame, context);
  308. }
  309. CFRelease (frame);
  310. }
  311. static void createLayout (TextLayout& glyphLayout, const AttributedString& text)
  312. {
  313. const CGFloat boundsHeight = 1.0e6f;
  314. CTFrameRef frame = createCTFrame (text, CGRectMake (0, 0, glyphLayout.getWidth(), boundsHeight));
  315. CFArrayRef lines = CTFrameGetLines (frame);
  316. const CFIndex numLines = CFArrayGetCount (lines);
  317. glyphLayout.ensureStorageAllocated ((int) numLines);
  318. for (CFIndex i = 0; i < numLines; ++i)
  319. {
  320. CTLineRef line = (CTLineRef) CFArrayGetValueAtIndex (lines, i);
  321. CFArrayRef runs = CTLineGetGlyphRuns (line);
  322. const CFIndex numRuns = CFArrayGetCount (runs);
  323. const CFRange cfrlineStringRange = CTLineGetStringRange (line);
  324. const CFIndex lineStringEnd = cfrlineStringRange.location + cfrlineStringRange.length - 1;
  325. const Range<int> lineStringRange ((int) cfrlineStringRange.location, (int) lineStringEnd);
  326. LineInfo lineInfo (frame, line, i);
  327. TextLayout::Line* const glyphLine = new TextLayout::Line (lineStringRange,
  328. Point<float> ((float) lineInfo.origin.x,
  329. (float) (boundsHeight - lineInfo.origin.y)),
  330. (float) lineInfo.ascent,
  331. (float) lineInfo.descent,
  332. (float) lineInfo.leading,
  333. (int) numRuns);
  334. glyphLayout.addLine (glyphLine);
  335. for (CFIndex j = 0; j < numRuns; ++j)
  336. {
  337. CTRunRef run = (CTRunRef) CFArrayGetValueAtIndex (runs, j);
  338. const CFIndex numGlyphs = CTRunGetGlyphCount (run);
  339. const CFRange runStringRange = CTRunGetStringRange (run);
  340. TextLayout::Run* const glyphRun = new TextLayout::Run (Range<int> ((int) runStringRange.location,
  341. (int) (runStringRange.location + runStringRange.length - 1)),
  342. (int) numGlyphs);
  343. glyphLine->runs.add (glyphRun);
  344. CFDictionaryRef runAttributes = CTRunGetAttributes (run);
  345. CTFontRef ctRunFont;
  346. if (CFDictionaryGetValueIfPresent (runAttributes, kCTFontAttributeName, (const void **) &ctRunFont))
  347. {
  348. CFStringRef cfsFontName = CTFontCopyPostScriptName (ctRunFont);
  349. CTFontRef ctFontRef = CTFontCreateWithName (cfsFontName, referenceFontSize, nullptr);
  350. CFRelease (cfsFontName);
  351. const float fontHeightToPointsFactor = getHeightToPointsFactor (ctFontRef);
  352. CFRelease (ctFontRef);
  353. CFStringRef cfsFontFamily = (CFStringRef) CTFontCopyAttribute (ctRunFont, kCTFontFamilyNameAttribute);
  354. CFStringRef cfsFontStyle = (CFStringRef) CTFontCopyAttribute (ctRunFont, kCTFontStyleNameAttribute);
  355. glyphRun->font = Font (String::fromCFString (cfsFontFamily),
  356. String::fromCFString (cfsFontStyle),
  357. (float) (CTFontGetSize (ctRunFont) / fontHeightToPointsFactor));
  358. CFRelease (cfsFontStyle);
  359. CFRelease (cfsFontFamily);
  360. }
  361. CGColorRef cgRunColor;
  362. if (CFDictionaryGetValueIfPresent (runAttributes, kCTForegroundColorAttributeName, (const void**) &cgRunColor)
  363. && CGColorGetNumberOfComponents (cgRunColor) == 4)
  364. {
  365. const CGFloat* const components = CGColorGetComponents (cgRunColor);
  366. glyphRun->colour = Colour::fromFloatRGBA ((float) components[0],
  367. (float) components[1],
  368. (float) components[2],
  369. (float) components[3]);
  370. }
  371. const Glyphs glyphs (run, (size_t) numGlyphs);
  372. const Advances advances (run, numGlyphs);
  373. const Positions positions (run, (size_t) numGlyphs);
  374. for (CFIndex k = 0; k < numGlyphs; ++k)
  375. glyphRun->glyphs.add (TextLayout::Glyph (glyphs.glyphs[k], Point<float> ((float) positions.points[k].x,
  376. (float) positions.points[k].y),
  377. (float) advances.advances[k].width));
  378. }
  379. }
  380. CFRelease (frame);
  381. }
  382. }
  383. //==============================================================================
  384. class OSXTypeface : public Typeface
  385. {
  386. public:
  387. OSXTypeface (const Font& font)
  388. : Typeface (font.getTypefaceName(),
  389. font.getTypefaceStyle()),
  390. fontRef (nullptr),
  391. ctFontRef (nullptr),
  392. fontHeightToPointsFactor (1.0f),
  393. renderingTransform (CGAffineTransformIdentity),
  394. attributedStringAtts (nullptr),
  395. ascent (0.0f),
  396. unitsToHeightScaleFactor (0.0f)
  397. {
  398. ctFontRef = CoreTextTypeLayout::createCTFont (font, referenceFontSize, renderingTransform);
  399. if (ctFontRef != nullptr)
  400. {
  401. fontRef = CTFontCopyGraphicsFont (ctFontRef, nullptr);
  402. initialiseMetrics();
  403. }
  404. }
  405. OSXTypeface (const void* data, size_t dataSize)
  406. : Typeface (String(), String()),
  407. fontRef (nullptr),
  408. ctFontRef (nullptr),
  409. fontHeightToPointsFactor (1.0f),
  410. renderingTransform (CGAffineTransformIdentity),
  411. attributedStringAtts (nullptr),
  412. ascent (0.0f),
  413. unitsToHeightScaleFactor (0.0f)
  414. {
  415. CFDataRef cfData = CFDataCreate (kCFAllocatorDefault, (const UInt8*) data, (CFIndex) dataSize);
  416. CGDataProviderRef provider = CGDataProviderCreateWithCFData (cfData);
  417. CFRelease (cfData);
  418. fontRef = CGFontCreateWithDataProvider (provider);
  419. CGDataProviderRelease (provider);
  420. if (fontRef != nullptr)
  421. {
  422. ctFontRef = CTFontCreateWithGraphicsFont (fontRef, referenceFontSize, nullptr, nullptr);
  423. if (ctFontRef != nullptr)
  424. {
  425. if (CFStringRef fontName = CTFontCopyName (ctFontRef, kCTFontFamilyNameKey))
  426. {
  427. name = String::fromCFString (fontName);
  428. CFRelease (fontName);
  429. }
  430. if (CFStringRef fontStyle = CTFontCopyName (ctFontRef, kCTFontStyleNameKey))
  431. {
  432. style = String::fromCFString (fontStyle);
  433. CFRelease (fontStyle);
  434. }
  435. initialiseMetrics();
  436. }
  437. }
  438. }
  439. void initialiseMetrics()
  440. {
  441. const float ctAscent = std::abs ((float) CTFontGetAscent (ctFontRef));
  442. const float ctDescent = std::abs ((float) CTFontGetDescent (ctFontRef));
  443. const float ctTotalHeight = ctAscent + ctDescent;
  444. ascent = ctAscent / ctTotalHeight;
  445. unitsToHeightScaleFactor = 1.0f / ctTotalHeight;
  446. pathTransform = AffineTransform::identity.scale (unitsToHeightScaleFactor);
  447. fontHeightToPointsFactor = referenceFontSize / ctTotalHeight;
  448. const short zero = 0;
  449. CFNumberRef numberRef = CFNumberCreate (0, kCFNumberShortType, &zero);
  450. CFStringRef keys[] = { kCTFontAttributeName, kCTLigatureAttributeName };
  451. CFTypeRef values[] = { ctFontRef, numberRef };
  452. attributedStringAtts = CFDictionaryCreate (nullptr, (const void**) &keys, (const void**) &values, numElementsInArray (keys),
  453. &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
  454. CFRelease (numberRef);
  455. }
  456. ~OSXTypeface()
  457. {
  458. if (attributedStringAtts != nullptr)
  459. CFRelease (attributedStringAtts);
  460. if (fontRef != nullptr)
  461. CGFontRelease (fontRef);
  462. if (ctFontRef != nullptr)
  463. CFRelease (ctFontRef);
  464. }
  465. float getAscent() const { return ascent; }
  466. float getDescent() const { return 1.0f - ascent; }
  467. float getHeightToPointsFactor() const { return fontHeightToPointsFactor; }
  468. float getStringWidth (const String& text)
  469. {
  470. float x = 0;
  471. if (ctFontRef != nullptr && text.isNotEmpty())
  472. {
  473. CFStringRef cfText = text.toCFString();
  474. CFAttributedStringRef attribString = CFAttributedStringCreate (kCFAllocatorDefault, cfText, attributedStringAtts);
  475. CFRelease (cfText);
  476. CTLineRef line = CTLineCreateWithAttributedString (attribString);
  477. CFArrayRef runArray = CTLineGetGlyphRuns (line);
  478. for (CFIndex i = 0; i < CFArrayGetCount (runArray); ++i)
  479. {
  480. CTRunRef run = (CTRunRef) CFArrayGetValueAtIndex (runArray, i);
  481. CFIndex length = CTRunGetGlyphCount (run);
  482. const CoreTextTypeLayout::Advances advances (run, length);
  483. for (int j = 0; j < length; ++j)
  484. x += (float) advances.advances[j].width;
  485. }
  486. CFRelease (line);
  487. CFRelease (attribString);
  488. x *= unitsToHeightScaleFactor;
  489. }
  490. return x;
  491. }
  492. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  493. {
  494. xOffsets.add (0);
  495. if (ctFontRef != nullptr && text.isNotEmpty())
  496. {
  497. float x = 0;
  498. CFStringRef cfText = text.toCFString();
  499. CFAttributedStringRef attribString = CFAttributedStringCreate (kCFAllocatorDefault, cfText, attributedStringAtts);
  500. CFRelease (cfText);
  501. CTLineRef line = CTLineCreateWithAttributedString (attribString);
  502. CFArrayRef runArray = CTLineGetGlyphRuns (line);
  503. for (CFIndex i = 0; i < CFArrayGetCount (runArray); ++i)
  504. {
  505. CTRunRef run = (CTRunRef) CFArrayGetValueAtIndex (runArray, i);
  506. CFIndex length = CTRunGetGlyphCount (run);
  507. const CoreTextTypeLayout::Advances advances (run, length);
  508. const CoreTextTypeLayout::Glyphs glyphs (run, (size_t) length);
  509. for (int j = 0; j < length; ++j)
  510. {
  511. x += (float) advances.advances[j].width;
  512. xOffsets.add (x * unitsToHeightScaleFactor);
  513. resultGlyphs.add (glyphs.glyphs[j]);
  514. }
  515. }
  516. CFRelease (line);
  517. CFRelease (attribString);
  518. }
  519. }
  520. EdgeTable* getEdgeTableForGlyph (int glyphNumber, const AffineTransform& transform)
  521. {
  522. Path path;
  523. if (getOutlineForGlyph (glyphNumber, path) && ! path.isEmpty())
  524. return new EdgeTable (path.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  525. path, transform);
  526. return nullptr;
  527. }
  528. bool getOutlineForGlyph (int glyphNumber, Path& path)
  529. {
  530. jassert (path.isEmpty()); // we might need to apply a transform to the path, so this must be empty
  531. CGPathRef pathRef = CTFontCreatePathForGlyph (ctFontRef, (CGGlyph) glyphNumber, &renderingTransform);
  532. if (pathRef == 0)
  533. return false;
  534. CGPathApply (pathRef, &path, pathApplier);
  535. CFRelease (pathRef);
  536. if (! pathTransform.isIdentity())
  537. path.applyTransform (pathTransform);
  538. return true;
  539. }
  540. //==============================================================================
  541. CGFontRef fontRef;
  542. CTFontRef ctFontRef;
  543. float fontHeightToPointsFactor;
  544. CGAffineTransform renderingTransform;
  545. private:
  546. CFDictionaryRef attributedStringAtts;
  547. float ascent, unitsToHeightScaleFactor;
  548. AffineTransform pathTransform;
  549. static void pathApplier (void* info, const CGPathElement* const element)
  550. {
  551. Path& path = *static_cast<Path*> (info);
  552. const CGPoint* const p = element->points;
  553. switch (element->type)
  554. {
  555. case kCGPathElementMoveToPoint: path.startNewSubPath ((float) p[0].x, (float) -p[0].y); break;
  556. case kCGPathElementAddLineToPoint: path.lineTo ((float) p[0].x, (float) -p[0].y); break;
  557. case kCGPathElementAddQuadCurveToPoint: path.quadraticTo ((float) p[0].x, (float) -p[0].y,
  558. (float) p[1].x, (float) -p[1].y); break;
  559. case kCGPathElementAddCurveToPoint: path.cubicTo ((float) p[0].x, (float) -p[0].y,
  560. (float) p[1].x, (float) -p[1].y,
  561. (float) p[2].x, (float) -p[2].y); break;
  562. case kCGPathElementCloseSubpath: path.closeSubPath(); break;
  563. default: jassertfalse; break;
  564. }
  565. }
  566. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OSXTypeface)
  567. };
  568. CTFontRef getCTFontFromTypeface (const Font& f)
  569. {
  570. if (OSXTypeface* tf = dynamic_cast <OSXTypeface*> (f.getTypeface()))
  571. return tf->ctFontRef;
  572. return 0;
  573. }
  574. StringArray Font::findAllTypefaceNames()
  575. {
  576. StringArray names;
  577. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5 && ! JUCE_IOS
  578. // CTFontManager only exists on OS X 10.6 and later, it does not exist on iOS
  579. CFArrayRef fontFamilyArray = CTFontManagerCopyAvailableFontFamilyNames();
  580. for (CFIndex i = 0; i < CFArrayGetCount (fontFamilyArray); ++i)
  581. {
  582. const String family (String::fromCFString ((CFStringRef) CFArrayGetValueAtIndex (fontFamilyArray, i)));
  583. if (! family.startsWithChar ('.')) // ignore fonts that start with a '.'
  584. names.addIfNotAlreadyThere (family);
  585. }
  586. CFRelease (fontFamilyArray);
  587. #else
  588. CTFontCollectionRef fontCollectionRef = CTFontCollectionCreateFromAvailableFonts (nullptr);
  589. CFArrayRef fontDescriptorArray = CTFontCollectionCreateMatchingFontDescriptors (fontCollectionRef);
  590. CFRelease (fontCollectionRef);
  591. for (CFIndex i = 0; i < CFArrayGetCount (fontDescriptorArray); ++i)
  592. {
  593. CTFontDescriptorRef ctFontDescriptorRef = (CTFontDescriptorRef) CFArrayGetValueAtIndex (fontDescriptorArray, i);
  594. CFStringRef cfsFontFamily = (CFStringRef) CTFontDescriptorCopyAttribute (ctFontDescriptorRef, kCTFontFamilyNameAttribute);
  595. names.addIfNotAlreadyThere (String::fromCFString (cfsFontFamily));
  596. CFRelease (cfsFontFamily);
  597. }
  598. CFRelease (fontDescriptorArray);
  599. #endif
  600. names.sort (true);
  601. return names;
  602. }
  603. StringArray Font::findAllTypefaceStyles (const String& family)
  604. {
  605. if (FontStyleHelpers::isPlaceholderFamilyName (family))
  606. return findAllTypefaceStyles (FontStyleHelpers::getConcreteFamilyNameFromPlaceholder (family));
  607. StringArray results;
  608. CFStringRef cfsFontFamily = family.toCFString();
  609. CFStringRef keys[] = { kCTFontFamilyNameAttribute };
  610. CFTypeRef values[] = { cfsFontFamily };
  611. CFDictionaryRef fontDescAttributes = CFDictionaryCreate (nullptr, (const void**) &keys, (const void**) &values, numElementsInArray (keys), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
  612. CFRelease (cfsFontFamily);
  613. CTFontDescriptorRef ctFontDescRef = CTFontDescriptorCreateWithAttributes (fontDescAttributes);
  614. CFRelease (fontDescAttributes);
  615. CFArrayRef fontFamilyArray = CFArrayCreate (kCFAllocatorDefault, (const void**) &ctFontDescRef, 1, &kCFTypeArrayCallBacks);
  616. CFRelease (ctFontDescRef);
  617. CTFontCollectionRef fontCollectionRef = CTFontCollectionCreateWithFontDescriptors (fontFamilyArray, nullptr);
  618. CFRelease (fontFamilyArray);
  619. CFArrayRef fontDescriptorArray = CTFontCollectionCreateMatchingFontDescriptors (fontCollectionRef);
  620. CFRelease (fontCollectionRef);
  621. if (fontDescriptorArray != nullptr)
  622. {
  623. for (CFIndex i = 0; i < CFArrayGetCount (fontDescriptorArray); ++i)
  624. {
  625. CTFontDescriptorRef ctFontDescriptorRef = (CTFontDescriptorRef) CFArrayGetValueAtIndex (fontDescriptorArray, i);
  626. CFStringRef cfsFontStyle = (CFStringRef) CTFontDescriptorCopyAttribute (ctFontDescriptorRef, kCTFontStyleNameAttribute);
  627. results.add (String::fromCFString (cfsFontStyle));
  628. CFRelease (cfsFontStyle);
  629. }
  630. CFRelease (fontDescriptorArray);
  631. }
  632. return results;
  633. }
  634. #else
  635. //==============================================================================
  636. // The stuff that follows is a mash-up that supports pre-OSX 10.5 APIs.
  637. // (Hopefully all of this can be ditched at some point in the future).
  638. //==============================================================================
  639. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  640. #define SUPPORT_10_4_FONTS 1
  641. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  642. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  643. #define SUPPORT_ONLY_10_4_FONTS 1
  644. #endif
  645. } // (juce namespace)
  646. @interface NSFont (PrivateHack)
  647. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  648. @end
  649. namespace juce
  650. {
  651. #endif
  652. //==============================================================================
  653. class OSXTypeface : public Typeface
  654. {
  655. public:
  656. OSXTypeface (const Font& font)
  657. : Typeface (font.getTypefaceName(), font.getTypefaceStyle())
  658. {
  659. JUCE_AUTORELEASEPOOL
  660. {
  661. renderingTransform = CGAffineTransformIdentity;
  662. NSDictionary* nsDict = [NSDictionary dictionaryWithObjectsAndKeys:
  663. juceStringToNS (name), NSFontFamilyAttribute,
  664. juceStringToNS (style), NSFontFaceAttribute, nil];
  665. NSFontDescriptor* nsFontDesc = [NSFontDescriptor fontDescriptorWithFontAttributes: nsDict];
  666. nsFont = [NSFont fontWithDescriptor: nsFontDesc size: referenceFontSize];
  667. [nsFont retain];
  668. #if SUPPORT_ONLY_10_4_FONTS
  669. initWithATSFont();
  670. #else
  671. #if SUPPORT_10_4_FONTS
  672. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  673. {
  674. initWithATSFont();
  675. }
  676. else
  677. #endif
  678. {
  679. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  680. const float absAscent = std::abs ((float) CGFontGetAscent (fontRef));
  681. const float totalHeight = absAscent + std::abs ((float) CGFontGetDescent (fontRef));
  682. ascent = absAscent / totalHeight;
  683. unitsToHeightScaleFactor = 1.0f / totalHeight;
  684. const float nsFontAscent = std::abs ([nsFont ascender]);
  685. const float nsFontDescent = std::abs ([nsFont descender]);
  686. fontHeightToPointsFactor = referenceFontSize / (nsFontAscent + nsFontDescent);
  687. }
  688. #endif
  689. pathTransform = AffineTransform::identity.scale (unitsToHeightScaleFactor);
  690. }
  691. }
  692. ~OSXTypeface()
  693. {
  694. #if ! JUCE_IOS
  695. [nsFont release];
  696. #endif
  697. if (fontRef != 0)
  698. CGFontRelease (fontRef);
  699. }
  700. #if SUPPORT_10_4_FONTS
  701. void initWithATSFont()
  702. {
  703. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  704. if (atsFont == 0)
  705. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  706. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  707. const float absAscent = std::abs ([nsFont ascender]);
  708. const float absDescent = std::abs ([nsFont descender]);
  709. const float totalHeight = absAscent + absDescent;
  710. unitsToHeightScaleFactor = 1.0f / totalHeight;
  711. fontHeightToPointsFactor = referenceFontSize / totalHeight;
  712. ascent = absAscent / totalHeight;
  713. }
  714. #endif
  715. float getAscent() const { return ascent; }
  716. float getDescent() const { return 1.0f - ascent; }
  717. float getHeightToPointsFactor() const { return fontHeightToPointsFactor; }
  718. float getStringWidth (const String& text)
  719. {
  720. if (fontRef == 0 || text.isEmpty())
  721. return 0;
  722. const int length = text.length();
  723. HeapBlock <CGGlyph> glyphs;
  724. createGlyphsForString (text.getCharPointer(), length, glyphs);
  725. float x = 0;
  726. #if SUPPORT_ONLY_10_4_FONTS
  727. HeapBlock <NSSize> advances (length);
  728. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  729. for (int i = 0; i < length; ++i)
  730. x += advances[i].width;
  731. #else
  732. #if SUPPORT_10_4_FONTS
  733. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  734. {
  735. HeapBlock <NSSize> advances (length);
  736. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  737. for (int i = 0; i < length; ++i)
  738. x += advances[i].width;
  739. }
  740. else
  741. #endif
  742. {
  743. HeapBlock <int> advances (length);
  744. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  745. for (int i = 0; i < length; ++i)
  746. x += advances[i];
  747. }
  748. #endif
  749. return x * unitsToHeightScaleFactor;
  750. }
  751. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  752. {
  753. xOffsets.add (0);
  754. if (fontRef == 0 || text.isEmpty())
  755. return;
  756. const int length = text.length();
  757. HeapBlock <CGGlyph> glyphs;
  758. createGlyphsForString (text.getCharPointer(), length, glyphs);
  759. #if SUPPORT_ONLY_10_4_FONTS
  760. HeapBlock <NSSize> advances (length);
  761. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  762. int x = 0;
  763. for (int i = 0; i < length; ++i)
  764. {
  765. x += advances[i].width;
  766. xOffsets.add (x * unitsToHeightScaleFactor);
  767. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  768. }
  769. #else
  770. #if SUPPORT_10_4_FONTS
  771. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  772. {
  773. HeapBlock <NSSize> advances (length);
  774. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  775. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  776. float x = 0;
  777. for (int i = 0; i < length; ++i)
  778. {
  779. x += advances[i].width;
  780. xOffsets.add (x * unitsToHeightScaleFactor);
  781. resultGlyphs.add (nsGlyphs[i]);
  782. }
  783. }
  784. else
  785. #endif
  786. {
  787. HeapBlock <int> advances (length);
  788. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  789. {
  790. int x = 0;
  791. for (int i = 0; i < length; ++i)
  792. {
  793. x += advances [i];
  794. xOffsets.add (x * unitsToHeightScaleFactor);
  795. resultGlyphs.add (glyphs[i]);
  796. }
  797. }
  798. }
  799. #endif
  800. }
  801. EdgeTable* getEdgeTableForGlyph (int glyphNumber, const AffineTransform& transform)
  802. {
  803. Path path;
  804. if (getOutlineForGlyph (glyphNumber, path) && ! path.isEmpty())
  805. return new EdgeTable (path.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  806. path, transform);
  807. return nullptr;
  808. }
  809. bool getOutlineForGlyph (int glyphNumber, Path& path)
  810. {
  811. #if JUCE_IOS
  812. return false;
  813. #else
  814. if (nsFont == nil)
  815. return false;
  816. // we might need to apply a transform to the path, so it mustn't have anything else in it
  817. jassert (path.isEmpty());
  818. JUCE_AUTORELEASEPOOL
  819. {
  820. NSBezierPath* bez = [NSBezierPath bezierPath];
  821. [bez moveToPoint: NSMakePoint (0, 0)];
  822. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  823. inFont: nsFont];
  824. for (int i = 0; i < [bez elementCount]; ++i)
  825. {
  826. NSPoint p[3];
  827. switch ([bez elementAtIndex: i associatedPoints: p])
  828. {
  829. case NSMoveToBezierPathElement: path.startNewSubPath ((float) p[0].x, (float) -p[0].y); break;
  830. case NSLineToBezierPathElement: path.lineTo ((float) p[0].x, (float) -p[0].y); break;
  831. case NSCurveToBezierPathElement: path.cubicTo ((float) p[0].x, (float) -p[0].y,
  832. (float) p[1].x, (float) -p[1].y,
  833. (float) p[2].x, (float) -p[2].y); break;
  834. case NSClosePathBezierPathElement: path.closeSubPath(); break;
  835. default: jassertfalse; break;
  836. }
  837. }
  838. path.applyTransform (pathTransform);
  839. }
  840. return true;
  841. #endif
  842. }
  843. //==============================================================================
  844. CGFontRef fontRef;
  845. float fontHeightToPointsFactor;
  846. CGAffineTransform renderingTransform;
  847. private:
  848. float ascent, unitsToHeightScaleFactor;
  849. #if ! JUCE_IOS
  850. NSFont* nsFont;
  851. AffineTransform pathTransform;
  852. #endif
  853. void createGlyphsForString (String::CharPointerType text, const int length, HeapBlock <CGGlyph>& glyphs)
  854. {
  855. #if SUPPORT_10_4_FONTS
  856. #if ! SUPPORT_ONLY_10_4_FONTS
  857. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  858. #endif
  859. {
  860. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  861. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  862. for (int i = 0; i < length; ++i)
  863. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text.getAndAdvance()];
  864. return;
  865. }
  866. #endif
  867. #if ! SUPPORT_ONLY_10_4_FONTS
  868. if (charToGlyphMapper == nullptr)
  869. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  870. glyphs.malloc (length);
  871. for (int i = 0; i < length; ++i)
  872. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text.getAndAdvance());
  873. #endif
  874. }
  875. #if ! SUPPORT_ONLY_10_4_FONTS
  876. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  877. class CharToGlyphMapper
  878. {
  879. public:
  880. CharToGlyphMapper (CGFontRef cgFontRef)
  881. : segCount (0), endCode (0), startCode (0), idDelta (0),
  882. idRangeOffset (0), glyphIndexes (0)
  883. {
  884. CFDataRef cmapTable = CGFontCopyTableForTag (cgFontRef, 'cmap');
  885. if (cmapTable != 0)
  886. {
  887. const int numSubtables = getValue16 (cmapTable, 2);
  888. for (int i = 0; i < numSubtables; ++i)
  889. {
  890. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  891. {
  892. const int offset = getValue32 (cmapTable, i * 8 + 8);
  893. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  894. {
  895. const int length = getValue16 (cmapTable, offset + 2);
  896. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  897. segCount = segCountX2 / 2;
  898. const int endCodeOffset = offset + 14;
  899. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  900. const int idDeltaOffset = startCodeOffset + segCountX2;
  901. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  902. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  903. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  904. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  905. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  906. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  907. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  908. }
  909. break;
  910. }
  911. }
  912. CFRelease (cmapTable);
  913. }
  914. }
  915. ~CharToGlyphMapper()
  916. {
  917. if (endCode != 0)
  918. {
  919. CFRelease (endCode);
  920. CFRelease (startCode);
  921. CFRelease (idDelta);
  922. CFRelease (idRangeOffset);
  923. CFRelease (glyphIndexes);
  924. }
  925. }
  926. int getGlyphForCharacter (const juce_wchar c) const
  927. {
  928. for (int i = 0; i < segCount; ++i)
  929. {
  930. if (getValue16 (endCode, i * 2) >= c)
  931. {
  932. const int start = getValue16 (startCode, i * 2);
  933. if (start > c)
  934. break;
  935. const int delta = getValue16 (idDelta, i * 2);
  936. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  937. if (rangeOffset == 0)
  938. return delta + c;
  939. else
  940. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  941. }
  942. }
  943. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  944. return jmax (-1, (int) c - 29);
  945. }
  946. private:
  947. int segCount;
  948. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  949. static uint16 getValue16 (CFDataRef data, const int index)
  950. {
  951. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  952. }
  953. static uint32 getValue32 (CFDataRef data, const int index)
  954. {
  955. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  956. }
  957. };
  958. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  959. #endif
  960. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OSXTypeface)
  961. };
  962. StringArray Font::findAllTypefaceNames()
  963. {
  964. StringArray names;
  965. JUCE_AUTORELEASEPOOL
  966. {
  967. #if JUCE_IOS
  968. for (NSString* name in [UIFont familyNames])
  969. #else
  970. for (NSString* name in [[NSFontManager sharedFontManager] availableFontFamilies])
  971. #endif
  972. names.add (nsStringToJuce (name));
  973. names.sort (true);
  974. }
  975. return names;
  976. }
  977. StringArray Font::findAllTypefaceStyles (const String& family)
  978. {
  979. if (FontStyleHelpers::isPlaceholderFamilyName (family))
  980. return findAllTypefaceStyles (FontStyleHelpers::getConcreteFamilyNameFromPlaceholder (family));
  981. StringArray results;
  982. JUCE_AUTORELEASEPOOL
  983. {
  984. for (NSArray* style in [[NSFontManager sharedFontManager] availableMembersOfFontFamily: juceStringToNS (family)])
  985. results.add (nsStringToJuce ((NSString*) [style objectAtIndex: 1]));
  986. }
  987. return results;
  988. }
  989. #endif
  990. //==============================================================================
  991. Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  992. {
  993. return new OSXTypeface (font);
  994. }
  995. Typeface::Ptr Typeface::createSystemTypefaceFor (const void* data, size_t dataSize)
  996. {
  997. return new OSXTypeface (data, dataSize);
  998. }
  999. void Typeface::scanFolderForFonts (const File&)
  1000. {
  1001. jassertfalse; // not implemented on this platform
  1002. }
  1003. struct DefaultFontNames
  1004. {
  1005. DefaultFontNames()
  1006. #if JUCE_IOS
  1007. : defaultSans ("Helvetica"),
  1008. defaultSerif ("Times New Roman"),
  1009. defaultFixed ("Courier New"),
  1010. #else
  1011. : defaultSans ("Lucida Grande"),
  1012. defaultSerif ("Times New Roman"),
  1013. defaultFixed ("Menlo"),
  1014. #endif
  1015. defaultFallback ("Arial Unicode MS")
  1016. {
  1017. }
  1018. String defaultSans, defaultSerif, defaultFixed, defaultFallback;
  1019. };
  1020. Typeface::Ptr Font::getDefaultTypefaceForFont (const Font& font)
  1021. {
  1022. static DefaultFontNames defaultNames;
  1023. Font newFont (font);
  1024. const String& faceName = font.getTypefaceName();
  1025. if (faceName == getDefaultSansSerifFontName()) newFont.setTypefaceName (defaultNames.defaultSans);
  1026. else if (faceName == getDefaultSerifFontName()) newFont.setTypefaceName (defaultNames.defaultSerif);
  1027. else if (faceName == getDefaultMonospacedFontName()) newFont.setTypefaceName (defaultNames.defaultFixed);
  1028. if (font.getTypefaceStyle() == getDefaultStyle())
  1029. newFont.setTypefaceStyle ("Regular");
  1030. return Typeface::createSystemTypefaceFor (newFont);
  1031. }
  1032. bool TextLayout::createNativeLayout (const AttributedString& text)
  1033. {
  1034. #if JUCE_CORETEXT_AVAILABLE
  1035. CoreTextTypeLayout::createLayout (*this, text);
  1036. return true;
  1037. #else
  1038. (void) text;
  1039. return false;
  1040. #endif
  1041. }