CCDevice-linux.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. /****************************************************************************
  2. Copyright (c) 2011 Laschweinski
  3. Copyright (c) 2013-2017 Chukong Technologies Inc.
  4. http://www.cocos2d-x.org
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. ****************************************************************************/
  21. #include "platform/CCPlatformConfig.h"
  22. #if CC_TARGET_PLATFORM == CC_PLATFORM_LINUX
  23. #include "platform/CCDevice.h"
  24. #include "platform/CCFileUtils.h"
  25. #include <X11/Xlib.h>
  26. #include <stdio.h>
  27. #include <algorithm>
  28. #include <vector>
  29. #include <map>
  30. #include <string>
  31. #include <sstream>
  32. #include <fontconfig/fontconfig.h>
  33. #include "ft2build.h"
  34. #include FT_FREETYPE_H
  35. using namespace std;
  36. // as FcFontMatch is quite an expensive call, cache the results of getFontFile
  37. static std::map<std::string, std::string> fontCache;
  38. struct LineBreakGlyph {
  39. FT_UInt glyphIndex;
  40. int paintPosition;
  41. int glyphWidth;
  42. int bearingX;
  43. int kerning;
  44. int horizAdvance;
  45. };
  46. struct LineBreakLine {
  47. LineBreakLine() : lineWidth(0) {}
  48. std::vector<LineBreakGlyph> glyphs;
  49. int lineWidth;
  50. void reset() {
  51. glyphs.clear();
  52. lineWidth = 0;
  53. }
  54. void calculateWidth() {
  55. lineWidth = 0;
  56. if ( glyphs.empty() == false ) {
  57. LineBreakGlyph& glyph = glyphs.at(glyphs.size() - 1);
  58. lineWidth = glyph.paintPosition + max(glyph.glyphWidth, glyph.horizAdvance - glyph.bearingX);
  59. }
  60. }
  61. };
  62. NS_CC_BEGIN
  63. int Device::getDPI()
  64. {
  65. static int dpi = -1;
  66. if (dpi == -1)
  67. {
  68. Display *dpy;
  69. char *displayname = NULL;
  70. int scr = 0; /* Screen number */
  71. dpy = XOpenDisplay (displayname);
  72. /*
  73. * there are 2.54 centimeters to an inch; so there are 25.4 millimeters.
  74. *
  75. * dpi = N pixels / (M millimeters / (25.4 millimeters / 1 inch))
  76. * = N pixels / (M inch / 25.4)
  77. * = N * 25.4 pixels / M inch
  78. */
  79. double xres = ((((double) DisplayWidth(dpy,scr)) * 25.4) /
  80. ((double) DisplayWidthMM(dpy,scr)));
  81. dpi = (int) (xres + 0.5);
  82. //printf("dpi = %d\n", dpi);
  83. XCloseDisplay (dpy);
  84. }
  85. return dpi;
  86. }
  87. void Device::setAccelerometerEnabled(bool isEnabled)
  88. {
  89. }
  90. void Device::setAccelerometerInterval(float interval)
  91. {
  92. }
  93. class BitmapDC
  94. {
  95. public:
  96. BitmapDC() {
  97. libError = FT_Init_FreeType( &library );
  98. FcInit();
  99. _data = NULL;
  100. reset();
  101. }
  102. ~BitmapDC() {
  103. FT_Done_FreeType(library);
  104. FcFini();
  105. reset();
  106. }
  107. void reset() {
  108. iMaxLineWidth = 0;
  109. iMaxLineHeight = 0;
  110. textLines.clear();
  111. }
  112. int utf8(char **p)
  113. {
  114. if ((**p & 0x80) == 0x00)
  115. {
  116. int a = *((*p)++);
  117. return a;
  118. }
  119. if ((**p & 0xE0) == 0xC0)
  120. {
  121. int a = *((*p)++) & 0x1F;
  122. int b = *((*p)++) & 0x3F;
  123. return (a << 6) | b;
  124. }
  125. if ((**p & 0xF0) == 0xE0)
  126. {
  127. int a = *((*p)++) & 0x0F;
  128. int b = *((*p)++) & 0x3F;
  129. int c = *((*p)++) & 0x3F;
  130. return (a << 12) | (b << 6) | c;
  131. }
  132. if ((**p & 0xF8) == 0xF0)
  133. {
  134. int a = *((*p)++) & 0x07;
  135. int b = *((*p)++) & 0x3F;
  136. int c = *((*p)++) & 0x3F;
  137. int d = *((*p)++) & 0x3F;
  138. return (a << 18) | (b << 12) | (c << 8) | d;
  139. }
  140. return 0;
  141. }
  142. bool isBreakPoint(FT_UInt currentCharacter, FT_UInt previousCharacter) {
  143. if ( previousCharacter == '-' || previousCharacter == '/' || previousCharacter == '\\' ) {
  144. // we can insert a line break after one of these characters
  145. return true;
  146. }
  147. return false;
  148. }
  149. bool divideString(FT_Face face, const char* sText, int iMaxWidth, int iMaxHeight) {
  150. const char* pText = sText;
  151. textLines.clear();
  152. iMaxLineWidth = 0;
  153. FT_UInt unicode;
  154. FT_UInt prevCharacter = 0;
  155. FT_UInt glyphIndex = 0;
  156. FT_UInt prevGlyphIndex = 0;
  157. FT_Vector delta;
  158. LineBreakLine currentLine;
  159. int currentPaintPosition = 0;
  160. int firstBreakIndex = -1;
  161. int lastBreakIndex = -1;
  162. bool hasKerning = FT_HAS_KERNING( face );
  163. while ((unicode=utf8((char**)&pText))) {
  164. if (unicode == '\n') {
  165. currentLine.calculateWidth();
  166. iMaxLineWidth = max(iMaxLineWidth, currentLine.lineWidth);
  167. textLines.push_back(currentLine);
  168. currentLine.reset();
  169. prevGlyphIndex = 0;
  170. prevCharacter = 0;
  171. firstBreakIndex = -1;
  172. lastBreakIndex = -1;
  173. currentPaintPosition = 0;
  174. continue;
  175. }
  176. if ( isBreakPoint(unicode, prevCharacter) ) {
  177. lastBreakIndex = currentLine.glyphs.size() - 1;
  178. }
  179. glyphIndex = FT_Get_Char_Index(face, unicode);
  180. if (FT_Load_Glyph(face, glyphIndex, FT_LOAD_DEFAULT)) {
  181. return false;
  182. }
  183. LineBreakGlyph glyph;
  184. glyph.glyphIndex = glyphIndex;
  185. glyph.glyphWidth = face->glyph->metrics.width >> 6;
  186. glyph.bearingX = face->glyph->metrics.horiBearingX >> 6;
  187. glyph.horizAdvance = face->glyph->metrics.horiAdvance >> 6;
  188. glyph.kerning = 0;
  189. if (prevGlyphIndex != 0 && hasKerning) {
  190. FT_Get_Kerning(face, prevGlyphIndex, glyphIndex, FT_KERNING_DEFAULT, &delta);
  191. glyph.kerning = delta.x >> 6;
  192. }
  193. if (iswspace(unicode)) {
  194. prevGlyphIndex = glyphIndex;
  195. prevCharacter = unicode;
  196. lastBreakIndex = currentLine.glyphs.size();
  197. if (firstBreakIndex == -1)
  198. firstBreakIndex = lastBreakIndex;
  199. } else {
  200. if (iswspace(prevCharacter))
  201. lastBreakIndex = currentLine.glyphs.size();
  202. if (iMaxWidth > 0 && currentPaintPosition + glyph.bearingX + glyph.kerning + glyph.glyphWidth > iMaxWidth) {
  203. int glyphCount = currentLine.glyphs.size();
  204. if ( lastBreakIndex >= 0 && lastBreakIndex < glyphCount && currentPaintPosition + glyph.bearingX + glyph.kerning + glyph.glyphWidth - currentLine.glyphs.at(lastBreakIndex).paintPosition < iMaxWidth ) {
  205. // we insert a line break at our last break opportunity
  206. std::vector<LineBreakGlyph> tempGlyphs;
  207. std::vector<LineBreakGlyph>::iterator it = currentLine.glyphs.begin();
  208. std::advance(it, lastBreakIndex);
  209. tempGlyphs.insert(tempGlyphs.begin(), it, currentLine.glyphs.end());
  210. if (firstBreakIndex == -1) {
  211. currentLine.glyphs.erase(it, currentLine.glyphs.end());
  212. } else {
  213. it = currentLine.glyphs.begin();
  214. std::advance(it, firstBreakIndex);
  215. currentLine.glyphs.erase(it, currentLine.glyphs.end());
  216. }
  217. currentLine.calculateWidth();
  218. iMaxLineWidth = max(iMaxLineWidth, currentLine.lineWidth);
  219. textLines.push_back(currentLine);
  220. currentLine.reset();
  221. currentPaintPosition = 0;
  222. for ( auto& glyph : tempGlyphs ) {
  223. if ( currentLine.glyphs.empty() ) {
  224. currentPaintPosition = -glyph.bearingX;
  225. glyph.kerning = 0;
  226. }
  227. glyph.paintPosition = currentPaintPosition + glyph.bearingX + glyph.kerning;
  228. currentLine.glyphs.push_back(glyph);
  229. currentPaintPosition += glyph.kerning + glyph.horizAdvance;
  230. }
  231. } else {
  232. // the current word is too big to fit into one line, insert line break right here
  233. currentPaintPosition = 0;
  234. glyph.kerning = 0;
  235. currentLine.calculateWidth();
  236. iMaxLineWidth = max(iMaxLineWidth, currentLine.lineWidth);
  237. textLines.push_back(currentLine);
  238. currentLine.reset();
  239. }
  240. prevGlyphIndex = 0;
  241. prevCharacter = 0;
  242. firstBreakIndex = -1;
  243. lastBreakIndex = -1;
  244. } else {
  245. prevGlyphIndex = glyphIndex;
  246. prevCharacter = unicode;
  247. }
  248. }
  249. if ( currentLine.glyphs.empty() ) {
  250. currentPaintPosition = -glyph.bearingX;
  251. }
  252. glyph.paintPosition = currentPaintPosition + glyph.bearingX + glyph.kerning;
  253. currentLine.glyphs.push_back(glyph);
  254. currentPaintPosition += glyph.kerning + glyph.horizAdvance;
  255. }
  256. if ( currentLine.glyphs.empty() == false ) {
  257. currentLine.calculateWidth();
  258. iMaxLineWidth = max(iMaxLineWidth, currentLine.lineWidth);
  259. textLines.push_back(currentLine);
  260. }
  261. return true;
  262. }
  263. /**
  264. * compute the start pos of every line
  265. */
  266. int computeLineStart(FT_Face face, Device::TextAlign eAlignMask, int line) {
  267. int lineWidth = textLines.at(line).lineWidth;
  268. if (eAlignMask == Device::TextAlign::CENTER || eAlignMask == Device::TextAlign::TOP || eAlignMask == Device::TextAlign::BOTTOM) {
  269. return (iMaxLineWidth - lineWidth) / 2;
  270. } else if (eAlignMask == Device::TextAlign::RIGHT || eAlignMask == Device::TextAlign::TOP_RIGHT || eAlignMask == Device::TextAlign::BOTTOM_RIGHT) {
  271. return (iMaxLineWidth - lineWidth);
  272. }
  273. // left or other situation
  274. return 0;
  275. }
  276. int computeLineStartY( FT_Face face, Device::TextAlign eAlignMask, int txtHeight, int borderHeight ){
  277. int baseLinePos = ceilf(face->size->metrics.ascender/64.0f);
  278. if (eAlignMask == Device::TextAlign::CENTER || eAlignMask == Device::TextAlign::LEFT || eAlignMask == Device::TextAlign::RIGHT) {
  279. //vertical center
  280. return (borderHeight - txtHeight) / 2 + baseLinePos;
  281. } else if (eAlignMask == Device::TextAlign::BOTTOM_RIGHT || eAlignMask == Device::TextAlign::BOTTOM || eAlignMask == Device::TextAlign::BOTTOM_LEFT) {
  282. //vertical bottom
  283. return borderHeight - txtHeight + baseLinePos;
  284. }
  285. // top alignment
  286. return baseLinePos;
  287. }
  288. std::string getFontFile(const char* family_name) {
  289. std::string fontPath = family_name;
  290. std::map<std::string, std::string>::iterator it = fontCache.find(family_name);
  291. if ( it != fontCache.end() ) {
  292. return it->second;
  293. }
  294. // check if the parameter is a font file shipped with the application
  295. std::string lowerCasePath = fontPath;
  296. std::transform(lowerCasePath.begin(), lowerCasePath.end(), lowerCasePath.begin(), ::tolower);
  297. if ( lowerCasePath.find(".ttf") != std::string::npos ) {
  298. fontPath = cocos2d::FileUtils::getInstance()->fullPathForFilename(fontPath.c_str());
  299. FILE *f = fopen(fontPath.c_str(), "r");
  300. if ( f ) {
  301. fclose(f);
  302. fontCache.insert(std::pair<std::string, std::string>(family_name, fontPath));
  303. return fontPath;
  304. }
  305. }
  306. // use fontconfig to match the parameter against the fonts installed on the system
  307. FcPattern *pattern = FcPatternBuild (0, FC_FAMILY, FcTypeString, family_name, (char *) 0);
  308. FcConfigSubstitute(0, pattern, FcMatchPattern);
  309. FcDefaultSubstitute(pattern);
  310. FcResult result;
  311. FcPattern *font = FcFontMatch(0, pattern, &result);
  312. if ( font ) {
  313. FcChar8 *s = NULL;
  314. if ( FcPatternGetString(font, FC_FILE, 0, &s) == FcResultMatch ) {
  315. fontPath = (const char*)s;
  316. FcPatternDestroy(font);
  317. FcPatternDestroy(pattern);
  318. fontCache.insert(std::pair<std::string, std::string>(family_name, fontPath));
  319. return fontPath;
  320. }
  321. FcPatternDestroy(font);
  322. }
  323. FcPatternDestroy(pattern);
  324. return family_name;
  325. }
  326. bool getBitmap(const char *text, const FontDefinition& textDefinition, Device::TextAlign eAlignMask) {
  327. if (libError) {
  328. return false;
  329. }
  330. FT_Face face;
  331. std::string fontfile = getFontFile(textDefinition._fontName.c_str());
  332. if ( FT_New_Face(library, fontfile.c_str(), 0, &face) ) {
  333. //no valid font found use default
  334. if ( FT_New_Face(library, "/usr/share/fonts/truetype/freefont/FreeSerif.ttf", 0, &face) ) {
  335. return false;
  336. }
  337. }
  338. //select utf8 charmap
  339. if ( FT_Select_Charmap(face, FT_ENCODING_UNICODE) ) {
  340. FT_Done_Face(face);
  341. return false;
  342. }
  343. if ( FT_Set_Pixel_Sizes(face, textDefinition._fontSize, textDefinition._fontSize) ) {
  344. FT_Done_Face(face);
  345. return false;
  346. }
  347. if ( divideString(face, text, textDefinition._dimensions.width, textDefinition._dimensions.height) == false ) {
  348. FT_Done_Face(face);
  349. return false;
  350. }
  351. //compute the final line width
  352. iMaxLineWidth = MAX(iMaxLineWidth, textDefinition._dimensions.width);
  353. //compute the final line height
  354. int lineHeight = face->size->metrics.height>>6;
  355. int txtHeight = (lineHeight * textLines.size());
  356. iMaxLineHeight = MAX(txtHeight, textDefinition._dimensions.height);
  357. _data = (unsigned char*)malloc(sizeof(unsigned char) * (iMaxLineWidth * iMaxLineHeight * 4));
  358. memset(_data,0, iMaxLineWidth * iMaxLineHeight*4);
  359. int iCurYCursor = computeLineStartY(face, eAlignMask, txtHeight, iMaxLineHeight);
  360. int lineCount = textLines.size();
  361. for (int line = 0; line < lineCount; line++) {
  362. int iCurXCursor = computeLineStart(face, eAlignMask, line);
  363. int glyphCount = textLines.at(line).glyphs.size();
  364. for (int i = 0; i < glyphCount; i++) {
  365. LineBreakGlyph glyph = textLines.at(line).glyphs.at(i);
  366. if (FT_Load_Glyph(face, glyph.glyphIndex, FT_LOAD_RENDER)) {
  367. continue;
  368. }
  369. FT_Bitmap& bitmap = face->glyph->bitmap;
  370. int yoffset = iCurYCursor - (face->glyph->metrics.horiBearingY >> 6);
  371. int xoffset = iCurXCursor + glyph.paintPosition;
  372. for (int y = 0; y < bitmap.rows; ++y) {
  373. int iY = yoffset + y;
  374. if (iY>=iMaxLineHeight) {
  375. //exceed the height truncate
  376. break;
  377. }
  378. iY *= iMaxLineWidth;
  379. int bitmap_y = y * bitmap.width;
  380. for (int x = 0; x < bitmap.width; ++x) {
  381. unsigned char cTemp = bitmap.buffer[bitmap_y + x];
  382. if (cTemp == 0) {
  383. continue;
  384. }
  385. int iX = xoffset + x;
  386. //FIXME:wrong text color
  387. int iTemp = cTemp << 24 | cTemp << 16 | cTemp << 8 | cTemp;
  388. *(int*) &_data[(iY + iX) * 4 + 0] = iTemp;
  389. }
  390. }
  391. }
  392. // step to next line
  393. iCurYCursor += lineHeight;
  394. }
  395. // free face
  396. FT_Done_Face(face);
  397. return true;
  398. }
  399. public:
  400. FT_Library library;
  401. unsigned char *_data;
  402. int libError;
  403. std::vector<LineBreakLine> textLines;
  404. int iMaxLineWidth;
  405. int iMaxLineHeight;
  406. };
  407. static BitmapDC& sharedBitmapDC()
  408. {
  409. static BitmapDC s_BmpDC;
  410. return s_BmpDC;
  411. }
  412. Data Device::getTextureDataForText(const char * text, const FontDefinition& textDefinition, TextAlign align, int &width, int &height, bool& hasPremultipliedAlpha)
  413. {
  414. Data ret;
  415. do
  416. {
  417. BitmapDC &dc = sharedBitmapDC();
  418. CC_BREAK_IF(! dc.getBitmap(text, textDefinition, align));
  419. CC_BREAK_IF(! dc._data);
  420. width = dc.iMaxLineWidth;
  421. height = dc.iMaxLineHeight;
  422. dc.reset();
  423. ret.fastSet(dc._data,width * height * 4);
  424. hasPremultipliedAlpha = true;
  425. } while (0);
  426. return ret;
  427. }
  428. void Device::setKeepScreenOn(bool /*value*/)
  429. {
  430. }
  431. void Device::vibrate(float /*duration*/)
  432. {
  433. }
  434. NS_CC_END
  435. #endif // CC_TARGET_PLATFORM == CC_PLATFORM_LINUX