CCDevice-mac.mm 13 KB

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