CCDevice-mac.mm 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. /****************************************************************************
  2. Copyright (c) 2010-2012 cocos2d-x.org
  3. Copyright (c) 2013-2016 Chukong Technologies Inc.
  4. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  5. http://www.cocos2d-x.org
  6. Permission is hereby granted, free of charge, to any person obtaining a copy
  7. of this software and associated documentation files (the "Software"), to deal
  8. in the Software without restriction, including without limitation the rights
  9. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. copies of the Software, and to permit persons to whom the Software is
  11. furnished to do so, subject to the following conditions:
  12. The above copyright notice and this permission notice shall be included in
  13. all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. THE SOFTWARE.
  21. ****************************************************************************/
  22. #include "platform/CCPlatformConfig.h"
  23. #if CC_TARGET_PLATFORM == CC_PLATFORM_MAC
  24. #include "platform/CCDevice.h"
  25. #include <Foundation/Foundation.h>
  26. #include <Cocoa/Cocoa.h>
  27. #include <string>
  28. #include "base/ccTypes.h"
  29. #include "platform/apple/CCDevice-apple.h"
  30. NS_CC_BEGIN
  31. static NSAttributedString* __attributedStringWithFontSize(NSMutableAttributedString* attributedString, CGFloat fontSize)
  32. {
  33. {
  34. [attributedString beginEditing];
  35. [attributedString enumerateAttribute:NSFontAttributeName inRange:NSMakeRange(0, attributedString.length) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) {
  36. NSFont* font = value;
  37. font = [[NSFontManager sharedFontManager] convertFont:font toSize:fontSize];
  38. [attributedString removeAttribute:NSFontAttributeName range:range];
  39. [attributedString addAttribute:NSFontAttributeName value:font range:range];
  40. }];
  41. [attributedString endEditing];
  42. }
  43. return [[attributedString copy] autorelease];
  44. }
  45. int Device::getDPI()
  46. {
  47. NSScreen *screen = [NSScreen mainScreen];
  48. NSDictionary *description = [screen deviceDescription];
  49. NSSize displayPixelSize = [[description objectForKey:NSDeviceSize] sizeValue];
  50. CGSize displayPhysicalSize = CGDisplayScreenSize([[description objectForKey:@"NSScreenNumber"] unsignedIntValue]);
  51. return ((displayPixelSize.width / displayPhysicalSize.width) * 25.4f);
  52. }
  53. void Device::setAccelerometerEnabled(bool isEnabled)
  54. {
  55. }
  56. void Device::setAccelerometerInterval(float interval)
  57. {
  58. }
  59. typedef struct
  60. {
  61. int height;
  62. int width;
  63. bool hasAlpha;
  64. bool isPremultipliedAlpha;
  65. unsigned char* data;
  66. } tImageInfo;
  67. static NSSize _calculateStringSize(NSAttributedString *str, id font, CGSize *constrainSize, bool enableWrap, int overflow)
  68. {
  69. NSSize textRect = NSZeroSize;
  70. textRect.width = constrainSize->width > 0 ? constrainSize->width
  71. : CGFLOAT_MAX;
  72. textRect.height = constrainSize->height > 0 ? constrainSize->height
  73. : CGFLOAT_MAX;
  74. if (overflow == 1) {
  75. if (!enableWrap) {
  76. textRect.width = CGFLOAT_MAX;
  77. textRect.height = CGFLOAT_MAX;
  78. } else {
  79. textRect.height = CGFLOAT_MAX;
  80. }
  81. }
  82. NSSize dim;
  83. #ifdef __MAC_10_11
  84. #if __MAC_OS_X_VERSION_MAX_ALLOWED >= __MAC_10_11
  85. dim = [str boundingRectWithSize:textRect options:(NSStringDrawingOptions)(NSStringDrawingUsesLineFragmentOrigin) context:nil].size;
  86. #else
  87. dim = [str boundingRectWithSize:textRect options:(NSStringDrawingOptions)(NSStringDrawingUsesLineFragmentOrigin)].size;
  88. #endif
  89. #else
  90. dim = [str boundingRectWithSize:textRect options:(NSStringDrawingOptions)(NSStringDrawingUsesLineFragmentOrigin)].size;
  91. #endif
  92. dim.width = ceilf(dim.width);
  93. dim.height = ceilf(dim.height);
  94. return dim;
  95. }
  96. static NSSize _calculateRealSizeForString(NSAttributedString **str, id font, NSSize constrainSize, bool enableWrap)
  97. {
  98. CGRect actualSize = CGRectMake(0, 0, constrainSize.width + 1, constrainSize.height + 1);
  99. int fontSize = [font pointSize];
  100. fontSize = fontSize + 1;
  101. if (!enableWrap) {
  102. while (actualSize.size.width > constrainSize.width ||
  103. actualSize.size.height > constrainSize.height) {
  104. fontSize = fontSize - 1;
  105. if (fontSize < 0) {
  106. actualSize = CGRectMake(0, 0, 0, 0);
  107. break;
  108. }
  109. NSMutableAttributedString *mutableString = [[*str mutableCopy] autorelease];
  110. *str = __attributedStringWithFontSize(mutableString, fontSize);
  111. #ifdef __MAC_10_11
  112. #if __MAC_OS_X_VERSION_MAX_ALLOWED >= __MAC_10_11
  113. CGSize fitSize = [*str boundingRectWithSize:CGSizeMake( CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
  114. #else
  115. CGSize fitSize = [*str boundingRectWithSize:CGSizeMake( CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin].size;
  116. #endif
  117. #else
  118. CGSize fitSize = [*str boundingRectWithSize:CGSizeMake( CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin].size;
  119. #endif
  120. if(fitSize.width == 0 || fitSize.height == 0) continue;
  121. actualSize.size = fitSize;
  122. if (constrainSize.width <= 0) {
  123. constrainSize.width = fitSize.width;
  124. }
  125. if (constrainSize.height <= 0){
  126. constrainSize.height = fitSize.height;
  127. }
  128. if(fontSize <= 0){
  129. break;
  130. }
  131. }
  132. }
  133. else {
  134. while (actualSize.size.height > constrainSize.height
  135. ||actualSize.size.width > constrainSize.width) {
  136. fontSize = fontSize - 1;
  137. if (fontSize < 0) {
  138. actualSize = CGRectMake(0, 0, 0, 0);
  139. break;
  140. }
  141. NSMutableAttributedString *mutableString = [[*str mutableCopy] autorelease];
  142. *str = __attributedStringWithFontSize(mutableString, fontSize);
  143. #ifdef __MAC_10_11
  144. #if __MAC_OS_X_VERSION_MAX_ALLOWED >= __MAC_10_11
  145. CGSize fitSize = [*str boundingRectWithSize:CGSizeMake( constrainSize.width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
  146. #else
  147. CGSize fitSize = [*str boundingRectWithSize:CGSizeMake( constrainSize.width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin].size;
  148. #endif
  149. #else
  150. CGSize fitSize = [*str boundingRectWithSize:CGSizeMake( constrainSize.width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin].size;
  151. #endif
  152. if(fitSize.width == 0 || fitSize.height == 0) continue;
  153. actualSize.size = fitSize;
  154. if (constrainSize.width <= 0) {
  155. constrainSize.width = fitSize.width;
  156. }
  157. if (constrainSize.height <= 0){
  158. constrainSize.height = fitSize.height;
  159. }
  160. if(fontSize <= 0){
  161. break;
  162. }
  163. }
  164. }
  165. return CGSizeMake(actualSize.size.width, actualSize.size.height);
  166. }
  167. static NSFont* _createSystemFont(const char* fontName, int size)
  168. {
  169. NSString * fntName = [NSString stringWithUTF8String:fontName];
  170. fntName = [[fntName lastPathComponent] stringByDeletingPathExtension];
  171. // font
  172. NSFont *font = [NSFont fontWithName:fntName size:size];
  173. if (font == nil) {
  174. font = [NSFont systemFontOfSize:size];
  175. }
  176. return font;
  177. }
  178. static CGFloat _calculateTextDrawStartHeight(cocos2d::Device::TextAlign align, CGSize realDimensions, CGSize dimensions)
  179. {
  180. float startH = 0;
  181. // vertical alignment
  182. unsigned int vAlignment = ((int)align >> 4) & 0x0F;
  183. switch (vAlignment) {
  184. //bottom
  185. case 1:startH = dimensions.height - realDimensions.height;break;
  186. //top
  187. case 2:startH = 0;break;
  188. //center
  189. case 3: startH = (dimensions.height - realDimensions.height) / 2;break;
  190. default:
  191. break;
  192. }
  193. return startH;
  194. }
  195. static bool _initWithString(const char * text, Device::TextAlign align, const char * fontName, int size, tImageInfo* info, const Color3B* fontColor, int fontAlpha, bool enableWrap, int overflow)
  196. {
  197. bool ret = false;
  198. CCASSERT(text, "Invalid text");
  199. CCASSERT(info, "Invalid info");
  200. do {
  201. NSString * string = [NSString stringWithUTF8String:text];
  202. CC_BREAK_IF(!string);
  203. id font = _createSystemFont(fontName, size);
  204. CC_BREAK_IF(!font);
  205. // color
  206. NSColor* foregroundColor;
  207. if (fontColor) {
  208. foregroundColor = [NSColor colorWithDeviceRed:fontColor->r/255.0
  209. green:fontColor->g/255.0
  210. blue:fontColor->b/255.0
  211. alpha:fontAlpha/255.0];
  212. } else {
  213. foregroundColor = [NSColor whiteColor];
  214. }
  215. // alignment
  216. NSTextAlignment textAlign = FontUtils::_calculateTextAlignment(align);
  217. NSMutableParagraphStyle *paragraphStyle = FontUtils::_calculateParagraphStyle(enableWrap, overflow);
  218. [paragraphStyle setAlignment:textAlign];
  219. // attribute
  220. NSDictionary* tokenAttributesDict = [NSDictionary dictionaryWithObjectsAndKeys:
  221. foregroundColor,NSForegroundColorAttributeName,
  222. font, NSFontAttributeName,
  223. paragraphStyle, NSParagraphStyleAttributeName, nil];
  224. NSAttributedString *stringWithAttributes =[[[NSAttributedString alloc] initWithString:string
  225. attributes:tokenAttributesDict] autorelease];
  226. CGSize dimensions = CGSizeMake(info->width, info->height);
  227. NSSize realDimensions;
  228. if (overflow == 2) {
  229. realDimensions = _calculateRealSizeForString(&stringWithAttributes, font, dimensions, enableWrap);
  230. } else {
  231. realDimensions = _calculateStringSize(stringWithAttributes, font, &dimensions, enableWrap, overflow);
  232. }
  233. // Mac crashes if the width or height is 0
  234. CC_BREAK_IF(realDimensions.width <= 0 || realDimensions.height <= 0);
  235. if(dimensions.width <= 0.f) {
  236. dimensions.width = realDimensions.width;
  237. }
  238. if (dimensions.height <= 0.f) {
  239. dimensions.height = realDimensions.height;
  240. }
  241. //Alignment
  242. CGFloat xPadding = FontUtils::_calculateTextDrawStartWidth(align, realDimensions, dimensions);
  243. CGFloat yPadding = _calculateTextDrawStartHeight(align, realDimensions, dimensions);
  244. NSInteger POTWide = dimensions.width;
  245. NSInteger POTHigh = dimensions.height;
  246. NSRect textRect = NSMakeRect(xPadding, POTHigh - dimensions.height + yPadding,
  247. realDimensions.width, realDimensions.height);
  248. [[NSGraphicsContext currentContext] setShouldAntialias:NO];
  249. NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize(POTWide, POTHigh)];
  250. [image lockFocus];
  251. // patch for mac retina display and lableTTF
  252. [[NSAffineTransform transform] set];
  253. [stringWithAttributes drawInRect:textRect];
  254. NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc] initWithFocusedViewRect:NSMakeRect (0.0f, 0.0f, POTWide, POTHigh)];
  255. [image unlockFocus];
  256. auto data = (unsigned char*) [bitmap bitmapData]; //Use the same buffer to improve the performance.
  257. NSUInteger textureSize = POTWide * POTHigh * 4;
  258. auto dataNew = (unsigned char*)malloc(sizeof(unsigned char) * textureSize);
  259. if (dataNew) {
  260. memcpy(dataNew, data, textureSize);
  261. // output params
  262. info->width = static_cast<int>(POTWide);
  263. info->height = static_cast<int>(POTHigh);
  264. info->data = dataNew;
  265. info->hasAlpha = true;
  266. info->isPremultipliedAlpha = true;
  267. ret = true;
  268. }
  269. [bitmap release];
  270. [image release];
  271. } while (0);
  272. return ret;
  273. }
  274. Data Device::getTextureDataForText(const char * text, const FontDefinition& textDefinition, TextAlign align, int &width, int &height, bool& hasPremultipliedAlpha)
  275. {
  276. Data ret;
  277. do {
  278. tImageInfo info = {0};
  279. info.width = textDefinition._dimensions.width;
  280. info.height = textDefinition._dimensions.height;
  281. if (! _initWithString(text, align, textDefinition._fontName.c_str(), textDefinition._fontSize, &info, &textDefinition._fontFillColor, textDefinition._fontAlpha, textDefinition._enableWrap, textDefinition._overflow))
  282. {
  283. break;
  284. }
  285. height = (short)info.height;
  286. width = (short)info.width;
  287. ret.fastSet(info.data,width * height * 4);
  288. hasPremultipliedAlpha = true;
  289. } while (0);
  290. return ret;
  291. }
  292. void Device::setKeepScreenOn(bool value)
  293. {
  294. }
  295. void Device::vibrate(float duration)
  296. {
  297. }
  298. NS_CC_END
  299. #endif // CC_TARGET_PLATFORM == CC_PLATFORM_MAC