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.

juce_android_Fonts.cpp 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 5 End-User License
  8. Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
  9. 27th April 2017).
  10. End User License Agreement: www.juce.com/juce-5-licence
  11. Privacy Policy: www.juce.com/juce-5-privacy-policy
  12. Or: You may also use this code under the terms of the GPL v3 (see
  13. www.gnu.org/licenses).
  14. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  15. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  16. DISCLAIMED.
  17. ==============================================================================
  18. */
  19. namespace juce
  20. {
  21. struct DefaultFontNames
  22. {
  23. DefaultFontNames()
  24. : defaultSans ("sans"),
  25. defaultSerif ("serif"),
  26. defaultFixed ("monospace"),
  27. defaultFallback ("sans")
  28. {
  29. }
  30. String getRealFontName (const String& faceName) const
  31. {
  32. if (faceName == Font::getDefaultSansSerifFontName()) return defaultSans;
  33. if (faceName == Font::getDefaultSerifFontName()) return defaultSerif;
  34. if (faceName == Font::getDefaultMonospacedFontName()) return defaultFixed;
  35. return faceName;
  36. }
  37. String defaultSans, defaultSerif, defaultFixed, defaultFallback;
  38. };
  39. Typeface::Ptr Font::getDefaultTypefaceForFont (const Font& font)
  40. {
  41. static DefaultFontNames defaultNames;
  42. Font f (font);
  43. f.setTypefaceName (defaultNames.getRealFontName (font.getTypefaceName()));
  44. return Typeface::createSystemTypefaceFor (f);
  45. }
  46. //==============================================================================
  47. #if JUCE_USE_FREETYPE
  48. StringArray FTTypefaceList::getDefaultFontDirectories()
  49. {
  50. return StringArray ("/system/fonts");
  51. }
  52. Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  53. {
  54. return new FreeTypeTypeface (font);
  55. }
  56. void Typeface::scanFolderForFonts (const File& folder)
  57. {
  58. FTTypefaceList::getInstance()->scanFontPaths (StringArray (folder.getFullPathName()));
  59. }
  60. StringArray Font::findAllTypefaceNames()
  61. {
  62. return FTTypefaceList::getInstance()->findAllFamilyNames();
  63. }
  64. StringArray Font::findAllTypefaceStyles (const String& family)
  65. {
  66. return FTTypefaceList::getInstance()->findAllTypefaceStyles (family);
  67. }
  68. bool TextLayout::createNativeLayout (const AttributedString&)
  69. {
  70. return false;
  71. }
  72. #else
  73. //==============================================================================
  74. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  75. STATICMETHOD (create, "create", "(Ljava/lang/String;I)Landroid/graphics/Typeface;") \
  76. STATICMETHOD (createFromFile, "createFromFile", "(Ljava/lang/String;)Landroid/graphics/Typeface;") \
  77. DECLARE_JNI_CLASS (TypefaceClass, "android/graphics/Typeface");
  78. #undef JNI_CLASS_MEMBERS
  79. //==============================================================================
  80. StringArray Font::findAllTypefaceNames()
  81. {
  82. StringArray results;
  83. Array<File> fonts;
  84. File ("/system/fonts").findChildFiles (fonts, File::findFiles, false, "*.ttf");
  85. for (int i = 0; i < fonts.size(); ++i)
  86. results.addIfNotAlreadyThere (fonts.getReference(i).getFileNameWithoutExtension()
  87. .upToLastOccurrenceOf ("-", false, false));
  88. return results;
  89. }
  90. StringArray Font::findAllTypefaceStyles (const String& family)
  91. {
  92. StringArray results ("Regular");
  93. Array<File> fonts;
  94. File ("/system/fonts").findChildFiles (fonts, File::findFiles, false, family + "-*.ttf");
  95. for (int i = 0; i < fonts.size(); ++i)
  96. results.addIfNotAlreadyThere (fonts.getReference(i).getFileNameWithoutExtension()
  97. .fromLastOccurrenceOf ("-", false, false));
  98. return results;
  99. }
  100. const float referenceFontSize = 256.0f;
  101. const float referenceFontToUnits = 1.0f / referenceFontSize;
  102. //==============================================================================
  103. class AndroidTypeface : public Typeface
  104. {
  105. public:
  106. AndroidTypeface (const Font& font)
  107. : Typeface (font.getTypefaceName(), font.getTypefaceStyle()),
  108. ascent (0), descent (0), heightToPointsFactor (1.0f)
  109. {
  110. JNIEnv* const env = getEnv();
  111. // First check whether there's an embedded asset with this font name:
  112. typeface = GlobalRef (android.activity.callObjectMethod (JuceAppActivity.getTypeFaceFromAsset,
  113. javaString ("fonts/" + name).get()));
  114. if (typeface.get() == nullptr)
  115. {
  116. const bool isBold = style.contains ("Bold");
  117. const bool isItalic = style.contains ("Italic");
  118. File fontFile (getFontFile (name, style));
  119. if (! fontFile.exists())
  120. fontFile = findFontFile (name, isBold, isItalic);
  121. if (fontFile.exists())
  122. typeface = GlobalRef (env->CallStaticObjectMethod (TypefaceClass, TypefaceClass.createFromFile,
  123. javaString (fontFile.getFullPathName()).get()));
  124. else
  125. typeface = GlobalRef (env->CallStaticObjectMethod (TypefaceClass, TypefaceClass.create,
  126. javaString (getName()).get(),
  127. (isBold ? 1 : 0) + (isItalic ? 2 : 0)));
  128. }
  129. initialise (env);
  130. }
  131. AndroidTypeface (const void* data, size_t size)
  132. : Typeface (String (static_cast<uint64> (reinterpret_cast<uintptr_t> (data))), String())
  133. {
  134. JNIEnv* const env = getEnv();
  135. LocalRef<jbyteArray> bytes (env->NewByteArray ((jsize) size));
  136. env->SetByteArrayRegion (bytes, 0, (jsize) size, (const jbyte*) data);
  137. typeface = GlobalRef (android.activity.callObjectMethod (JuceAppActivity.getTypeFaceFromByteArray, bytes.get()));
  138. initialise (env);
  139. }
  140. void initialise (JNIEnv* const env)
  141. {
  142. rect = GlobalRef (env->NewObject (RectClass, RectClass.constructor, 0, 0, 0, 0));
  143. paint = GlobalRef (GraphicsHelpers::createPaint (Graphics::highResamplingQuality));
  144. const LocalRef<jobject> ignored (paint.callObjectMethod (Paint.setTypeface, typeface.get()));
  145. paint.callVoidMethod (Paint.setTextSize, referenceFontSize);
  146. const float fullAscent = std::abs (paint.callFloatMethod (Paint.ascent));
  147. const float fullDescent = paint.callFloatMethod (Paint.descent);
  148. const float totalHeight = fullAscent + fullDescent;
  149. ascent = fullAscent / totalHeight;
  150. descent = fullDescent / totalHeight;
  151. heightToPointsFactor = referenceFontSize / totalHeight;
  152. }
  153. float getAscent() const override { return ascent; }
  154. float getDescent() const override { return descent; }
  155. float getHeightToPointsFactor() const override { return heightToPointsFactor; }
  156. float getStringWidth (const String& text) override
  157. {
  158. JNIEnv* env = getEnv();
  159. const int numChars = text.length();
  160. jfloatArray widths = env->NewFloatArray (numChars);
  161. const int numDone = paint.callIntMethod (Paint.getTextWidths, javaString (text).get(), widths);
  162. HeapBlock<jfloat> localWidths (static_cast<size_t> (numDone));
  163. env->GetFloatArrayRegion (widths, 0, numDone, localWidths);
  164. env->DeleteLocalRef (widths);
  165. float x = 0;
  166. for (int i = 0; i < numDone; ++i)
  167. x += localWidths[i];
  168. return x * referenceFontToUnits;
  169. }
  170. void getGlyphPositions (const String& text, Array<int>& glyphs, Array<float>& xOffsets) override
  171. {
  172. JNIEnv* env = getEnv();
  173. const int numChars = text.length();
  174. jfloatArray widths = env->NewFloatArray (numChars);
  175. const int numDone = paint.callIntMethod (Paint.getTextWidths, javaString (text).get(), widths);
  176. HeapBlock<jfloat> localWidths (static_cast<size_t> (numDone));
  177. env->GetFloatArrayRegion (widths, 0, numDone, localWidths);
  178. env->DeleteLocalRef (widths);
  179. String::CharPointerType s (text.getCharPointer());
  180. xOffsets.add (0);
  181. float x = 0;
  182. for (int i = 0; i < numDone; ++i)
  183. {
  184. const float local = localWidths[i];
  185. // Android uses jchar (UTF-16) characters
  186. jchar ch = (jchar) s.getAndAdvance();
  187. // Android has no proper glyph support, so we have to do
  188. // a hacky workaround for ligature detection
  189. #if JUCE_STRING_UTF_TYPE <= 16
  190. static_assert (sizeof (int) >= (sizeof (jchar) * 2), "Unable store two java chars in one glyph");
  191. // if the width of this glyph is zero inside the string but has
  192. // a width on it's own, then it's probably due to ligature
  193. if (local == 0.0f && glyphs.size() > 0 && getStringWidth (String (ch)) > 0.0f)
  194. {
  195. // modify the previous glyph
  196. int& glyphNumber = glyphs.getReference (glyphs.size() - 1);
  197. // make sure this is not a three character ligature
  198. if (glyphNumber < std::numeric_limits<jchar>::max())
  199. {
  200. const unsigned int previousGlyph
  201. = static_cast<unsigned int> (glyphNumber) & ((1U << (sizeof (jchar) * 8U)) - 1U);
  202. const unsigned int thisGlyph
  203. = static_cast<unsigned int> (ch) & ((1U << (sizeof (jchar) * 8U)) - 1U);
  204. glyphNumber = static_cast<int> ((thisGlyph << (sizeof (jchar) * 8U)) | previousGlyph);
  205. ch = 0;
  206. }
  207. }
  208. #endif
  209. glyphs.add ((int) ch);
  210. x += local;
  211. xOffsets.add (x * referenceFontToUnits);
  212. }
  213. }
  214. bool getOutlineForGlyph (int /*glyphNumber*/, Path& /*destPath*/) override
  215. {
  216. return false;
  217. }
  218. EdgeTable* getEdgeTableForGlyph (int glyphNumber, const AffineTransform& t, float /*fontHeight*/) override
  219. {
  220. #if JUCE_STRING_UTF_TYPE <= 16
  221. static_assert (sizeof (int) >= (sizeof (jchar) * 2), "Unable store two jni chars in one int");
  222. // glyphNumber of zero is used to indicate that the last character was a ligature
  223. if (glyphNumber == 0) return nullptr;
  224. jchar ch1 = (static_cast<unsigned int> (glyphNumber) >> 0) & ((1U << (sizeof (jchar) * 8U)) - 1U);
  225. jchar ch2 = (static_cast<unsigned int> (glyphNumber) >> (sizeof (jchar) * 8U)) & ((1U << (sizeof (jchar) * 8U)) - 1U);
  226. #else
  227. jchar ch1 = glyphNumber, ch2 = 0;
  228. #endif
  229. JNIEnv* env = getEnv();
  230. jobject matrix = GraphicsHelpers::createMatrix (env, AffineTransform::scale (referenceFontToUnits).followedBy (t));
  231. jintArray maskData = (jintArray) android.activity.callObjectMethod (JuceAppActivity.renderGlyph, ch1, ch2, paint.get(), matrix, rect.get());
  232. env->DeleteLocalRef (matrix);
  233. const int left = env->GetIntField (rect.get(), RectClass.left);
  234. const int top = env->GetIntField (rect.get(), RectClass.top);
  235. const int right = env->GetIntField (rect.get(), RectClass.right);
  236. const int bottom = env->GetIntField (rect.get(), RectClass.bottom);
  237. const Rectangle<int> bounds (left, top, right - left, bottom - top);
  238. EdgeTable* et = nullptr;
  239. if (! bounds.isEmpty())
  240. {
  241. et = new EdgeTable (bounds);
  242. jint* const maskDataElements = env->GetIntArrayElements (maskData, 0);
  243. const jint* mask = maskDataElements;
  244. for (int y = top; y < bottom; ++y)
  245. {
  246. #if JUCE_LITTLE_ENDIAN
  247. const uint8* const lineBytes = ((const uint8*) mask) + 3;
  248. #else
  249. const uint8* const lineBytes = (const uint8*) mask;
  250. #endif
  251. et->clipLineToMask (left, y, lineBytes, 4, bounds.getWidth());
  252. mask += bounds.getWidth();
  253. }
  254. env->ReleaseIntArrayElements (maskData, maskDataElements, 0);
  255. }
  256. env->DeleteLocalRef (maskData);
  257. return et;
  258. }
  259. GlobalRef typeface, paint, rect;
  260. float ascent, descent, heightToPointsFactor;
  261. private:
  262. static File findFontFile (const String& family,
  263. const bool bold, const bool italic)
  264. {
  265. File file;
  266. if (bold || italic)
  267. {
  268. String suffix;
  269. if (bold) suffix = "Bold";
  270. if (italic) suffix << "Italic";
  271. file = getFontFile (family, suffix);
  272. if (file.exists())
  273. return file;
  274. }
  275. file = getFontFile (family, "Regular");
  276. if (! file.exists())
  277. file = getFontFile (family, String());
  278. return file;
  279. }
  280. static File getFontFile (const String& family, const String& style)
  281. {
  282. String path ("/system/fonts/" + family);
  283. if (style.isNotEmpty())
  284. path << '-' << style;
  285. return File (path + ".ttf");
  286. }
  287. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidTypeface)
  288. };
  289. //==============================================================================
  290. Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  291. {
  292. return new AndroidTypeface (font);
  293. }
  294. Typeface::Ptr Typeface::createSystemTypefaceFor (const void* data, size_t size)
  295. {
  296. return new AndroidTypeface (data, size);
  297. }
  298. void Typeface::scanFolderForFonts (const File&)
  299. {
  300. jassertfalse; // not available unless using FreeType
  301. }
  302. bool TextLayout::createNativeLayout (const AttributedString&)
  303. {
  304. return false;
  305. }
  306. #endif
  307. } // namespace juce