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.

DDTTYLogger.m 54 KiB

3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482
  1. // Software License Agreement (BSD License)
  2. //
  3. // Copyright (c) 2010-2015, Deusty, LLC
  4. // All rights reserved.
  5. //
  6. // Redistribution and use of this software in source and binary forms,
  7. // with or without modification, are permitted provided that the following conditions are met:
  8. //
  9. // * Redistributions of source code must retain the above copyright notice,
  10. // this list of conditions and the following disclaimer.
  11. //
  12. // * Neither the name of Deusty nor the names of its contributors may be used
  13. // to endorse or promote products derived from this software without specific
  14. // prior written permission of Deusty, LLC.
  15. #import "DDTTYLogger.h"
  16. #import <unistd.h>
  17. #import <sys/uio.h>
  18. #if !__has_feature(objc_arc)
  19. #error This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC).
  20. #endif
  21. // We probably shouldn't be using DDLog() statements within the DDLog implementation.
  22. // But we still want to leave our log statements for any future debugging,
  23. // and to allow other developers to trace the implementation (which is a great learning tool).
  24. //
  25. // So we use primitive logging macros around NSLog.
  26. // We maintain the NS prefix on the macros to be explicit about the fact that we're using NSLog.
  27. #ifndef DD_NSLOG_LEVEL
  28. #define DD_NSLOG_LEVEL 2
  29. #endif
  30. #define NSLogError(frmt, ...) do{ if(DD_NSLOG_LEVEL >= 1) NSLog((frmt), ##__VA_ARGS__); } while(0)
  31. #define NSLogWarn(frmt, ...) do{ if(DD_NSLOG_LEVEL >= 2) NSLog((frmt), ##__VA_ARGS__); } while(0)
  32. #define NSLogInfo(frmt, ...) do{ if(DD_NSLOG_LEVEL >= 3) NSLog((frmt), ##__VA_ARGS__); } while(0)
  33. #define NSLogDebug(frmt, ...) do{ if(DD_NSLOG_LEVEL >= 4) NSLog((frmt), ##__VA_ARGS__); } while(0)
  34. #define NSLogVerbose(frmt, ...) do{ if(DD_NSLOG_LEVEL >= 5) NSLog((frmt), ##__VA_ARGS__); } while(0)
  35. // Xcode does NOT natively support colors in the Xcode debugging console.
  36. // You'll need to install the XcodeColors plugin to see colors in the Xcode console.
  37. // https://github.com/robbiehanson/XcodeColors
  38. //
  39. // The following is documentation from the XcodeColors project:
  40. //
  41. //
  42. // How to apply color formatting to your log statements:
  43. //
  44. // To set the foreground color:
  45. // Insert the ESCAPE_SEQ into your string, followed by "fg124,12,255;" where r=124, g=12, b=255.
  46. //
  47. // To set the background color:
  48. // Insert the ESCAPE_SEQ into your string, followed by "bg12,24,36;" where r=12, g=24, b=36.
  49. //
  50. // To reset the foreground color (to default value):
  51. // Insert the ESCAPE_SEQ into your string, followed by "fg;"
  52. //
  53. // To reset the background color (to default value):
  54. // Insert the ESCAPE_SEQ into your string, followed by "bg;"
  55. //
  56. // To reset the foreground and background color (to default values) in one operation:
  57. // Insert the ESCAPE_SEQ into your string, followed by ";"
  58. #define XCODE_COLORS_ESCAPE_SEQ "\033["
  59. #define XCODE_COLORS_RESET_FG XCODE_COLORS_ESCAPE_SEQ "fg;" // Clear any foreground color
  60. #define XCODE_COLORS_RESET_BG XCODE_COLORS_ESCAPE_SEQ "bg;" // Clear any background color
  61. #define XCODE_COLORS_RESET XCODE_COLORS_ESCAPE_SEQ ";" // Clear any foreground or background color
  62. // If running in a shell, not all RGB colors will be supported.
  63. // In this case we automatically map to the closest available color.
  64. // In order to provide this mapping, we have a hard-coded set of the standard RGB values available in the shell.
  65. // However, not every shell is the same, and Apple likes to think different even when it comes to shell colors.
  66. //
  67. // Map to standard Terminal.app colors (1), or
  68. // map to standard xterm colors (0).
  69. #define MAP_TO_TERMINAL_APP_COLORS 1
  70. @interface DDTTYLoggerColorProfile : NSObject {
  71. @public
  72. DDLogFlag mask;
  73. NSInteger context;
  74. uint8_t fg_r;
  75. uint8_t fg_g;
  76. uint8_t fg_b;
  77. uint8_t bg_r;
  78. uint8_t bg_g;
  79. uint8_t bg_b;
  80. NSUInteger fgCodeIndex;
  81. NSString *fgCodeRaw;
  82. NSUInteger bgCodeIndex;
  83. NSString *bgCodeRaw;
  84. char fgCode[24];
  85. size_t fgCodeLen;
  86. char bgCode[24];
  87. size_t bgCodeLen;
  88. char resetCode[8];
  89. size_t resetCodeLen;
  90. }
  91. - (instancetype)initWithForegroundColor:(DDColor *)fgColor backgroundColor:(DDColor *)bgColor flag:(DDLogFlag)mask context:(NSInteger)ctxt;
  92. @end
  93. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  94. #pragma mark -
  95. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  96. @interface DDTTYLogger () {
  97. NSUInteger _calendarUnitFlags;
  98. NSString *_appName;
  99. char *_app;
  100. size_t _appLen;
  101. NSString *_processID;
  102. char *_pid;
  103. size_t _pidLen;
  104. BOOL _colorsEnabled;
  105. NSMutableArray *_colorProfilesArray;
  106. NSMutableDictionary *_colorProfilesDict;
  107. }
  108. @end
  109. @implementation DDTTYLogger
  110. static BOOL isaColorTTY;
  111. static BOOL isaColor256TTY;
  112. static BOOL isaXcodeColorTTY;
  113. static NSArray *codes_fg = nil;
  114. static NSArray *codes_bg = nil;
  115. static NSArray *colors = nil;
  116. static DDTTYLogger *sharedInstance;
  117. /**
  118. * Initializes the colors array, as well as the codes_fg and codes_bg arrays, for 16 color mode.
  119. *
  120. * This method is used when the application is running from within a shell that only supports 16 color mode.
  121. * This method is not invoked if the application is running within Xcode, or via normal UI app launch.
  122. **/
  123. + (void)initialize_colors_16 {
  124. if (codes_fg || codes_bg || colors) {
  125. return;
  126. }
  127. NSMutableArray *m_codes_fg = [NSMutableArray arrayWithCapacity:16];
  128. NSMutableArray *m_codes_bg = [NSMutableArray arrayWithCapacity:16];
  129. NSMutableArray *m_colors = [NSMutableArray arrayWithCapacity:16];
  130. // In a standard shell only 16 colors are supported.
  131. //
  132. // More information about ansi escape codes can be found online.
  133. // http://en.wikipedia.org/wiki/ANSI_escape_code
  134. [m_codes_fg addObject:@"30m"]; // normal - black
  135. [m_codes_fg addObject:@"31m"]; // normal - red
  136. [m_codes_fg addObject:@"32m"]; // normal - green
  137. [m_codes_fg addObject:@"33m"]; // normal - yellow
  138. [m_codes_fg addObject:@"34m"]; // normal - blue
  139. [m_codes_fg addObject:@"35m"]; // normal - magenta
  140. [m_codes_fg addObject:@"36m"]; // normal - cyan
  141. [m_codes_fg addObject:@"37m"]; // normal - gray
  142. [m_codes_fg addObject:@"1;30m"]; // bright - darkgray
  143. [m_codes_fg addObject:@"1;31m"]; // bright - red
  144. [m_codes_fg addObject:@"1;32m"]; // bright - green
  145. [m_codes_fg addObject:@"1;33m"]; // bright - yellow
  146. [m_codes_fg addObject:@"1;34m"]; // bright - blue
  147. [m_codes_fg addObject:@"1;35m"]; // bright - magenta
  148. [m_codes_fg addObject:@"1;36m"]; // bright - cyan
  149. [m_codes_fg addObject:@"1;37m"]; // bright - white
  150. [m_codes_bg addObject:@"40m"]; // normal - black
  151. [m_codes_bg addObject:@"41m"]; // normal - red
  152. [m_codes_bg addObject:@"42m"]; // normal - green
  153. [m_codes_bg addObject:@"43m"]; // normal - yellow
  154. [m_codes_bg addObject:@"44m"]; // normal - blue
  155. [m_codes_bg addObject:@"45m"]; // normal - magenta
  156. [m_codes_bg addObject:@"46m"]; // normal - cyan
  157. [m_codes_bg addObject:@"47m"]; // normal - gray
  158. [m_codes_bg addObject:@"1;40m"]; // bright - darkgray
  159. [m_codes_bg addObject:@"1;41m"]; // bright - red
  160. [m_codes_bg addObject:@"1;42m"]; // bright - green
  161. [m_codes_bg addObject:@"1;43m"]; // bright - yellow
  162. [m_codes_bg addObject:@"1;44m"]; // bright - blue
  163. [m_codes_bg addObject:@"1;45m"]; // bright - magenta
  164. [m_codes_bg addObject:@"1;46m"]; // bright - cyan
  165. [m_codes_bg addObject:@"1;47m"]; // bright - white
  166. #if MAP_TO_TERMINAL_APP_COLORS
  167. // Standard Terminal.app colors:
  168. //
  169. // These are the default colors used by Apple's Terminal.app.
  170. [m_colors addObject:DDMakeColor( 0, 0, 0)]; // normal - black
  171. [m_colors addObject:DDMakeColor(194, 54, 33)]; // normal - red
  172. [m_colors addObject:DDMakeColor( 37, 188, 36)]; // normal - green
  173. [m_colors addObject:DDMakeColor(173, 173, 39)]; // normal - yellow
  174. [m_colors addObject:DDMakeColor( 73, 46, 225)]; // normal - blue
  175. [m_colors addObject:DDMakeColor(211, 56, 211)]; // normal - magenta
  176. [m_colors addObject:DDMakeColor( 51, 187, 200)]; // normal - cyan
  177. [m_colors addObject:DDMakeColor(203, 204, 205)]; // normal - gray
  178. [m_colors addObject:DDMakeColor(129, 131, 131)]; // bright - darkgray
  179. [m_colors addObject:DDMakeColor(252, 57, 31)]; // bright - red
  180. [m_colors addObject:DDMakeColor( 49, 231, 34)]; // bright - green
  181. [m_colors addObject:DDMakeColor(234, 236, 35)]; // bright - yellow
  182. [m_colors addObject:DDMakeColor( 88, 51, 255)]; // bright - blue
  183. [m_colors addObject:DDMakeColor(249, 53, 248)]; // bright - magenta
  184. [m_colors addObject:DDMakeColor( 20, 240, 240)]; // bright - cyan
  185. [m_colors addObject:DDMakeColor(233, 235, 235)]; // bright - white
  186. #else /* if MAP_TO_TERMINAL_APP_COLORS */
  187. // Standard xterm colors:
  188. //
  189. // These are the default colors used by most xterm shells.
  190. [m_colors addObject:DDMakeColor( 0, 0, 0)]; // normal - black
  191. [m_colors addObject:DDMakeColor(205, 0, 0)]; // normal - red
  192. [m_colors addObject:DDMakeColor( 0, 205, 0)]; // normal - green
  193. [m_colors addObject:DDMakeColor(205, 205, 0)]; // normal - yellow
  194. [m_colors addObject:DDMakeColor( 0, 0, 238)]; // normal - blue
  195. [m_colors addObject:DDMakeColor(205, 0, 205)]; // normal - magenta
  196. [m_colors addObject:DDMakeColor( 0, 205, 205)]; // normal - cyan
  197. [m_colors addObject:DDMakeColor(229, 229, 229)]; // normal - gray
  198. [m_colors addObject:DDMakeColor(127, 127, 127)]; // bright - darkgray
  199. [m_colors addObject:DDMakeColor(255, 0, 0)]; // bright - red
  200. [m_colors addObject:DDMakeColor( 0, 255, 0)]; // bright - green
  201. [m_colors addObject:DDMakeColor(255, 255, 0)]; // bright - yellow
  202. [m_colors addObject:DDMakeColor( 92, 92, 255)]; // bright - blue
  203. [m_colors addObject:DDMakeColor(255, 0, 255)]; // bright - magenta
  204. [m_colors addObject:DDMakeColor( 0, 255, 255)]; // bright - cyan
  205. [m_colors addObject:DDMakeColor(255, 255, 255)]; // bright - white
  206. #endif /* if MAP_TO_TERMINAL_APP_COLORS */
  207. codes_fg = [m_codes_fg copy];
  208. codes_bg = [m_codes_bg copy];
  209. colors = [m_colors copy];
  210. NSAssert([codes_fg count] == [codes_bg count], @"Invalid colors/codes array(s)");
  211. NSAssert([codes_fg count] == [colors count], @"Invalid colors/codes array(s)");
  212. }
  213. /**
  214. * Initializes the colors array, as well as the codes_fg and codes_bg arrays, for 256 color mode.
  215. *
  216. * This method is used when the application is running from within a shell that supports 256 color mode.
  217. * This method is not invoked if the application is running within Xcode, or via normal UI app launch.
  218. **/
  219. + (void)initialize_colors_256 {
  220. if (codes_fg || codes_bg || colors) {
  221. return;
  222. }
  223. NSMutableArray *m_codes_fg = [NSMutableArray arrayWithCapacity:(256 - 16)];
  224. NSMutableArray *m_codes_bg = [NSMutableArray arrayWithCapacity:(256 - 16)];
  225. NSMutableArray *m_colors = [NSMutableArray arrayWithCapacity:(256 - 16)];
  226. #if MAP_TO_TERMINAL_APP_COLORS
  227. // Standard Terminal.app colors:
  228. //
  229. // These are the colors the Terminal.app uses in xterm-256color mode.
  230. // In this mode, the terminal supports 256 different colors, specified by 256 color codes.
  231. //
  232. // The first 16 color codes map to the original 16 color codes supported by the earlier xterm-color mode.
  233. // These are actually configurable, and thus we ignore them for the purposes of mapping,
  234. // as we can't rely on them being constant. They are largely duplicated anyway.
  235. //
  236. // The next 216 color codes are designed to run the spectrum, with several shades of every color.
  237. // While the color codes are standardized, the actual RGB values for each color code is not.
  238. // Apple's Terminal.app uses different RGB values from that of a standard xterm.
  239. // Apple's choices in colors are designed to be a little nicer on the eyes.
  240. //
  241. // The last 24 color codes represent a grayscale.
  242. //
  243. // Unfortunately, unlike the standard xterm color chart,
  244. // Apple's RGB values cannot be calculated using a simple formula (at least not that I know of).
  245. // Also, I don't know of any ways to programmatically query the shell for the RGB values.
  246. // So this big giant color chart had to be made by hand.
  247. //
  248. // More information about ansi escape codes can be found online.
  249. // http://en.wikipedia.org/wiki/ANSI_escape_code
  250. // Colors
  251. [m_colors addObject:DDMakeColor( 47, 49, 49)];
  252. [m_colors addObject:DDMakeColor( 60, 42, 144)];
  253. [m_colors addObject:DDMakeColor( 66, 44, 183)];
  254. [m_colors addObject:DDMakeColor( 73, 46, 222)];
  255. [m_colors addObject:DDMakeColor( 81, 50, 253)];
  256. [m_colors addObject:DDMakeColor( 88, 51, 255)];
  257. [m_colors addObject:DDMakeColor( 42, 128, 37)];
  258. [m_colors addObject:DDMakeColor( 42, 127, 128)];
  259. [m_colors addObject:DDMakeColor( 44, 126, 169)];
  260. [m_colors addObject:DDMakeColor( 56, 125, 209)];
  261. [m_colors addObject:DDMakeColor( 59, 124, 245)];
  262. [m_colors addObject:DDMakeColor( 66, 123, 255)];
  263. [m_colors addObject:DDMakeColor( 51, 163, 41)];
  264. [m_colors addObject:DDMakeColor( 39, 162, 121)];
  265. [m_colors addObject:DDMakeColor( 42, 161, 162)];
  266. [m_colors addObject:DDMakeColor( 53, 160, 202)];
  267. [m_colors addObject:DDMakeColor( 45, 159, 240)];
  268. [m_colors addObject:DDMakeColor( 58, 158, 255)];
  269. [m_colors addObject:DDMakeColor( 31, 196, 37)];
  270. [m_colors addObject:DDMakeColor( 48, 196, 115)];
  271. [m_colors addObject:DDMakeColor( 39, 195, 155)];
  272. [m_colors addObject:DDMakeColor( 49, 195, 195)];
  273. [m_colors addObject:DDMakeColor( 32, 194, 235)];
  274. [m_colors addObject:DDMakeColor( 53, 193, 255)];
  275. [m_colors addObject:DDMakeColor( 50, 229, 35)];
  276. [m_colors addObject:DDMakeColor( 40, 229, 109)];
  277. [m_colors addObject:DDMakeColor( 27, 229, 149)];
  278. [m_colors addObject:DDMakeColor( 49, 228, 189)];
  279. [m_colors addObject:DDMakeColor( 33, 228, 228)];
  280. [m_colors addObject:DDMakeColor( 53, 227, 255)];
  281. [m_colors addObject:DDMakeColor( 27, 254, 30)];
  282. [m_colors addObject:DDMakeColor( 30, 254, 103)];
  283. [m_colors addObject:DDMakeColor( 45, 254, 143)];
  284. [m_colors addObject:DDMakeColor( 38, 253, 182)];
  285. [m_colors addObject:DDMakeColor( 38, 253, 222)];
  286. [m_colors addObject:DDMakeColor( 42, 253, 252)];
  287. [m_colors addObject:DDMakeColor(140, 48, 40)];
  288. [m_colors addObject:DDMakeColor(136, 51, 136)];
  289. [m_colors addObject:DDMakeColor(135, 52, 177)];
  290. [m_colors addObject:DDMakeColor(134, 52, 217)];
  291. [m_colors addObject:DDMakeColor(135, 56, 248)];
  292. [m_colors addObject:DDMakeColor(134, 53, 255)];
  293. [m_colors addObject:DDMakeColor(125, 125, 38)];
  294. [m_colors addObject:DDMakeColor(124, 125, 125)];
  295. [m_colors addObject:DDMakeColor(122, 124, 166)];
  296. [m_colors addObject:DDMakeColor(123, 124, 207)];
  297. [m_colors addObject:DDMakeColor(123, 122, 247)];
  298. [m_colors addObject:DDMakeColor(124, 121, 255)];
  299. [m_colors addObject:DDMakeColor(119, 160, 35)];
  300. [m_colors addObject:DDMakeColor(117, 160, 120)];
  301. [m_colors addObject:DDMakeColor(117, 160, 160)];
  302. [m_colors addObject:DDMakeColor(115, 159, 201)];
  303. [m_colors addObject:DDMakeColor(116, 158, 240)];
  304. [m_colors addObject:DDMakeColor(117, 157, 255)];
  305. [m_colors addObject:DDMakeColor(113, 195, 39)];
  306. [m_colors addObject:DDMakeColor(110, 194, 114)];
  307. [m_colors addObject:DDMakeColor(111, 194, 154)];
  308. [m_colors addObject:DDMakeColor(108, 194, 194)];
  309. [m_colors addObject:DDMakeColor(109, 193, 234)];
  310. [m_colors addObject:DDMakeColor(108, 192, 255)];
  311. [m_colors addObject:DDMakeColor(105, 228, 30)];
  312. [m_colors addObject:DDMakeColor(103, 228, 109)];
  313. [m_colors addObject:DDMakeColor(105, 228, 148)];
  314. [m_colors addObject:DDMakeColor(100, 227, 188)];
  315. [m_colors addObject:DDMakeColor( 99, 227, 227)];
  316. [m_colors addObject:DDMakeColor( 99, 226, 253)];
  317. [m_colors addObject:DDMakeColor( 92, 253, 34)];
  318. [m_colors addObject:DDMakeColor( 96, 253, 103)];
  319. [m_colors addObject:DDMakeColor( 97, 253, 142)];
  320. [m_colors addObject:DDMakeColor( 88, 253, 182)];
  321. [m_colors addObject:DDMakeColor( 93, 253, 221)];
  322. [m_colors addObject:DDMakeColor( 88, 254, 251)];
  323. [m_colors addObject:DDMakeColor(177, 53, 34)];
  324. [m_colors addObject:DDMakeColor(174, 54, 131)];
  325. [m_colors addObject:DDMakeColor(172, 55, 172)];
  326. [m_colors addObject:DDMakeColor(171, 57, 213)];
  327. [m_colors addObject:DDMakeColor(170, 55, 249)];
  328. [m_colors addObject:DDMakeColor(170, 57, 255)];
  329. [m_colors addObject:DDMakeColor(165, 123, 37)];
  330. [m_colors addObject:DDMakeColor(163, 123, 123)];
  331. [m_colors addObject:DDMakeColor(162, 123, 164)];
  332. [m_colors addObject:DDMakeColor(161, 122, 205)];
  333. [m_colors addObject:DDMakeColor(161, 121, 241)];
  334. [m_colors addObject:DDMakeColor(161, 121, 255)];
  335. [m_colors addObject:DDMakeColor(158, 159, 33)];
  336. [m_colors addObject:DDMakeColor(157, 158, 118)];
  337. [m_colors addObject:DDMakeColor(157, 158, 159)];
  338. [m_colors addObject:DDMakeColor(155, 157, 199)];
  339. [m_colors addObject:DDMakeColor(155, 157, 239)];
  340. [m_colors addObject:DDMakeColor(154, 156, 255)];
  341. [m_colors addObject:DDMakeColor(152, 193, 40)];
  342. [m_colors addObject:DDMakeColor(151, 193, 113)];
  343. [m_colors addObject:DDMakeColor(150, 193, 153)];
  344. [m_colors addObject:DDMakeColor(150, 192, 193)];
  345. [m_colors addObject:DDMakeColor(148, 192, 232)];
  346. [m_colors addObject:DDMakeColor(149, 191, 253)];
  347. [m_colors addObject:DDMakeColor(146, 227, 28)];
  348. [m_colors addObject:DDMakeColor(144, 227, 108)];
  349. [m_colors addObject:DDMakeColor(144, 227, 147)];
  350. [m_colors addObject:DDMakeColor(144, 227, 187)];
  351. [m_colors addObject:DDMakeColor(142, 226, 227)];
  352. [m_colors addObject:DDMakeColor(142, 225, 252)];
  353. [m_colors addObject:DDMakeColor(138, 253, 36)];
  354. [m_colors addObject:DDMakeColor(137, 253, 102)];
  355. [m_colors addObject:DDMakeColor(136, 253, 141)];
  356. [m_colors addObject:DDMakeColor(138, 254, 181)];
  357. [m_colors addObject:DDMakeColor(135, 255, 220)];
  358. [m_colors addObject:DDMakeColor(133, 255, 250)];
  359. [m_colors addObject:DDMakeColor(214, 57, 30)];
  360. [m_colors addObject:DDMakeColor(211, 59, 126)];
  361. [m_colors addObject:DDMakeColor(209, 57, 168)];
  362. [m_colors addObject:DDMakeColor(208, 55, 208)];
  363. [m_colors addObject:DDMakeColor(207, 58, 247)];
  364. [m_colors addObject:DDMakeColor(206, 61, 255)];
  365. [m_colors addObject:DDMakeColor(204, 121, 32)];
  366. [m_colors addObject:DDMakeColor(202, 121, 121)];
  367. [m_colors addObject:DDMakeColor(201, 121, 161)];
  368. [m_colors addObject:DDMakeColor(200, 120, 202)];
  369. [m_colors addObject:DDMakeColor(200, 120, 241)];
  370. [m_colors addObject:DDMakeColor(198, 119, 255)];
  371. [m_colors addObject:DDMakeColor(198, 157, 37)];
  372. [m_colors addObject:DDMakeColor(196, 157, 116)];
  373. [m_colors addObject:DDMakeColor(195, 156, 157)];
  374. [m_colors addObject:DDMakeColor(195, 156, 197)];
  375. [m_colors addObject:DDMakeColor(194, 155, 236)];
  376. [m_colors addObject:DDMakeColor(193, 155, 255)];
  377. [m_colors addObject:DDMakeColor(191, 192, 36)];
  378. [m_colors addObject:DDMakeColor(190, 191, 112)];
  379. [m_colors addObject:DDMakeColor(189, 191, 152)];
  380. [m_colors addObject:DDMakeColor(189, 191, 191)];
  381. [m_colors addObject:DDMakeColor(188, 190, 230)];
  382. [m_colors addObject:DDMakeColor(187, 190, 253)];
  383. [m_colors addObject:DDMakeColor(185, 226, 28)];
  384. [m_colors addObject:DDMakeColor(184, 226, 106)];
  385. [m_colors addObject:DDMakeColor(183, 225, 146)];
  386. [m_colors addObject:DDMakeColor(183, 225, 186)];
  387. [m_colors addObject:DDMakeColor(182, 225, 225)];
  388. [m_colors addObject:DDMakeColor(181, 224, 252)];
  389. [m_colors addObject:DDMakeColor(178, 255, 35)];
  390. [m_colors addObject:DDMakeColor(178, 255, 101)];
  391. [m_colors addObject:DDMakeColor(177, 254, 141)];
  392. [m_colors addObject:DDMakeColor(176, 254, 180)];
  393. [m_colors addObject:DDMakeColor(176, 254, 220)];
  394. [m_colors addObject:DDMakeColor(175, 253, 249)];
  395. [m_colors addObject:DDMakeColor(247, 56, 30)];
  396. [m_colors addObject:DDMakeColor(245, 57, 122)];
  397. [m_colors addObject:DDMakeColor(243, 59, 163)];
  398. [m_colors addObject:DDMakeColor(244, 60, 204)];
  399. [m_colors addObject:DDMakeColor(242, 59, 241)];
  400. [m_colors addObject:DDMakeColor(240, 55, 255)];
  401. [m_colors addObject:DDMakeColor(241, 119, 36)];
  402. [m_colors addObject:DDMakeColor(240, 120, 118)];
  403. [m_colors addObject:DDMakeColor(238, 119, 158)];
  404. [m_colors addObject:DDMakeColor(237, 119, 199)];
  405. [m_colors addObject:DDMakeColor(237, 118, 238)];
  406. [m_colors addObject:DDMakeColor(236, 118, 255)];
  407. [m_colors addObject:DDMakeColor(235, 154, 36)];
  408. [m_colors addObject:DDMakeColor(235, 154, 114)];
  409. [m_colors addObject:DDMakeColor(234, 154, 154)];
  410. [m_colors addObject:DDMakeColor(232, 154, 194)];
  411. [m_colors addObject:DDMakeColor(232, 153, 234)];
  412. [m_colors addObject:DDMakeColor(232, 153, 255)];
  413. [m_colors addObject:DDMakeColor(230, 190, 30)];
  414. [m_colors addObject:DDMakeColor(229, 189, 110)];
  415. [m_colors addObject:DDMakeColor(228, 189, 150)];
  416. [m_colors addObject:DDMakeColor(227, 189, 190)];
  417. [m_colors addObject:DDMakeColor(227, 189, 229)];
  418. [m_colors addObject:DDMakeColor(226, 188, 255)];
  419. [m_colors addObject:DDMakeColor(224, 224, 35)];
  420. [m_colors addObject:DDMakeColor(223, 224, 105)];
  421. [m_colors addObject:DDMakeColor(222, 224, 144)];
  422. [m_colors addObject:DDMakeColor(222, 223, 184)];
  423. [m_colors addObject:DDMakeColor(222, 223, 224)];
  424. [m_colors addObject:DDMakeColor(220, 223, 253)];
  425. [m_colors addObject:DDMakeColor(217, 253, 28)];
  426. [m_colors addObject:DDMakeColor(217, 253, 99)];
  427. [m_colors addObject:DDMakeColor(216, 252, 139)];
  428. [m_colors addObject:DDMakeColor(216, 252, 179)];
  429. [m_colors addObject:DDMakeColor(215, 252, 218)];
  430. [m_colors addObject:DDMakeColor(215, 251, 250)];
  431. [m_colors addObject:DDMakeColor(255, 61, 30)];
  432. [m_colors addObject:DDMakeColor(255, 60, 118)];
  433. [m_colors addObject:DDMakeColor(255, 58, 159)];
  434. [m_colors addObject:DDMakeColor(255, 56, 199)];
  435. [m_colors addObject:DDMakeColor(255, 55, 238)];
  436. [m_colors addObject:DDMakeColor(255, 59, 255)];
  437. [m_colors addObject:DDMakeColor(255, 117, 29)];
  438. [m_colors addObject:DDMakeColor(255, 117, 115)];
  439. [m_colors addObject:DDMakeColor(255, 117, 155)];
  440. [m_colors addObject:DDMakeColor(255, 117, 195)];
  441. [m_colors addObject:DDMakeColor(255, 116, 235)];
  442. [m_colors addObject:DDMakeColor(254, 116, 255)];
  443. [m_colors addObject:DDMakeColor(255, 152, 27)];
  444. [m_colors addObject:DDMakeColor(255, 152, 111)];
  445. [m_colors addObject:DDMakeColor(254, 152, 152)];
  446. [m_colors addObject:DDMakeColor(255, 152, 192)];
  447. [m_colors addObject:DDMakeColor(254, 151, 231)];
  448. [m_colors addObject:DDMakeColor(253, 151, 253)];
  449. [m_colors addObject:DDMakeColor(255, 187, 33)];
  450. [m_colors addObject:DDMakeColor(253, 187, 107)];
  451. [m_colors addObject:DDMakeColor(252, 187, 148)];
  452. [m_colors addObject:DDMakeColor(253, 187, 187)];
  453. [m_colors addObject:DDMakeColor(254, 187, 227)];
  454. [m_colors addObject:DDMakeColor(252, 186, 252)];
  455. [m_colors addObject:DDMakeColor(252, 222, 34)];
  456. [m_colors addObject:DDMakeColor(251, 222, 103)];
  457. [m_colors addObject:DDMakeColor(251, 222, 143)];
  458. [m_colors addObject:DDMakeColor(250, 222, 182)];
  459. [m_colors addObject:DDMakeColor(251, 221, 222)];
  460. [m_colors addObject:DDMakeColor(252, 221, 252)];
  461. [m_colors addObject:DDMakeColor(251, 252, 15)];
  462. [m_colors addObject:DDMakeColor(251, 252, 97)];
  463. [m_colors addObject:DDMakeColor(249, 252, 137)];
  464. [m_colors addObject:DDMakeColor(247, 252, 177)];
  465. [m_colors addObject:DDMakeColor(247, 253, 217)];
  466. [m_colors addObject:DDMakeColor(254, 255, 255)];
  467. // Grayscale
  468. [m_colors addObject:DDMakeColor( 52, 53, 53)];
  469. [m_colors addObject:DDMakeColor( 57, 58, 59)];
  470. [m_colors addObject:DDMakeColor( 66, 67, 67)];
  471. [m_colors addObject:DDMakeColor( 75, 76, 76)];
  472. [m_colors addObject:DDMakeColor( 83, 85, 85)];
  473. [m_colors addObject:DDMakeColor( 92, 93, 94)];
  474. [m_colors addObject:DDMakeColor(101, 102, 102)];
  475. [m_colors addObject:DDMakeColor(109, 111, 111)];
  476. [m_colors addObject:DDMakeColor(118, 119, 119)];
  477. [m_colors addObject:DDMakeColor(126, 127, 128)];
  478. [m_colors addObject:DDMakeColor(134, 136, 136)];
  479. [m_colors addObject:DDMakeColor(143, 144, 145)];
  480. [m_colors addObject:DDMakeColor(151, 152, 153)];
  481. [m_colors addObject:DDMakeColor(159, 161, 161)];
  482. [m_colors addObject:DDMakeColor(167, 169, 169)];
  483. [m_colors addObject:DDMakeColor(176, 177, 177)];
  484. [m_colors addObject:DDMakeColor(184, 185, 186)];
  485. [m_colors addObject:DDMakeColor(192, 193, 194)];
  486. [m_colors addObject:DDMakeColor(200, 201, 202)];
  487. [m_colors addObject:DDMakeColor(208, 209, 210)];
  488. [m_colors addObject:DDMakeColor(216, 218, 218)];
  489. [m_colors addObject:DDMakeColor(224, 226, 226)];
  490. [m_colors addObject:DDMakeColor(232, 234, 234)];
  491. [m_colors addObject:DDMakeColor(240, 242, 242)];
  492. // Color codes
  493. int index = 16;
  494. while (index < 256) {
  495. [m_codes_fg addObject:[NSString stringWithFormat:@"38;5;%dm", index]];
  496. [m_codes_bg addObject:[NSString stringWithFormat:@"48;5;%dm", index]];
  497. index++;
  498. }
  499. #else /* if MAP_TO_TERMINAL_APP_COLORS */
  500. // Standard xterm colors:
  501. //
  502. // These are the colors xterm shells use in xterm-256color mode.
  503. // In this mode, the shell supports 256 different colors, specified by 256 color codes.
  504. //
  505. // The first 16 color codes map to the original 16 color codes supported by the earlier xterm-color mode.
  506. // These are generally configurable, and thus we ignore them for the purposes of mapping,
  507. // as we can't rely on them being constant. They are largely duplicated anyway.
  508. //
  509. // The next 216 color codes are designed to run the spectrum, with several shades of every color.
  510. // The last 24 color codes represent a grayscale.
  511. //
  512. // While the color codes are standardized, the actual RGB values for each color code is not.
  513. // However most standard xterms follow a well known color chart,
  514. // which can easily be calculated using the simple formula below.
  515. //
  516. // More information about ansi escape codes can be found online.
  517. // http://en.wikipedia.org/wiki/ANSI_escape_code
  518. int index = 16;
  519. int r; // red
  520. int g; // green
  521. int b; // blue
  522. int ri; // r increment
  523. int gi; // g increment
  524. int bi; // b increment
  525. // Calculate xterm colors (using standard algorithm)
  526. int r = 0;
  527. int g = 0;
  528. int b = 0;
  529. for (ri = 0; ri < 6; ri++) {
  530. r = (ri == 0) ? 0 : 95 + (40 * (ri - 1));
  531. for (gi = 0; gi < 6; gi++) {
  532. g = (gi == 0) ? 0 : 95 + (40 * (gi - 1));
  533. for (bi = 0; bi < 6; bi++) {
  534. b = (bi == 0) ? 0 : 95 + (40 * (bi - 1));
  535. [m_codes_fg addObject:[NSString stringWithFormat:@"38;5;%dm", index]];
  536. [m_codes_bg addObject:[NSString stringWithFormat:@"48;5;%dm", index]];
  537. [m_colors addObject:DDMakeColor(r, g, b)];
  538. index++;
  539. }
  540. }
  541. }
  542. // Calculate xterm grayscale (using standard algorithm)
  543. r = 8;
  544. g = 8;
  545. b = 8;
  546. while (index < 256) {
  547. [m_codes_fg addObject:[NSString stringWithFormat:@"38;5;%dm", index]];
  548. [m_codes_bg addObject:[NSString stringWithFormat:@"48;5;%dm", index]];
  549. [m_colors addObject:DDMakeColor(r, g, b)];
  550. r += 10;
  551. g += 10;
  552. b += 10;
  553. index++;
  554. }
  555. #endif /* if MAP_TO_TERMINAL_APP_COLORS */
  556. codes_fg = [m_codes_fg copy];
  557. codes_bg = [m_codes_bg copy];
  558. colors = [m_colors copy];
  559. NSAssert([codes_fg count] == [codes_bg count], @"Invalid colors/codes array(s)");
  560. NSAssert([codes_fg count] == [colors count], @"Invalid colors/codes array(s)");
  561. }
  562. + (void)getRed:(CGFloat *)rPtr green:(CGFloat *)gPtr blue:(CGFloat *)bPtr fromColor:(DDColor *)color {
  563. #if TARGET_OS_IPHONE
  564. // iOS
  565. BOOL done = NO;
  566. if ([color respondsToSelector:@selector(getRed:green:blue:alpha:)]) {
  567. done = [color getRed:rPtr green:gPtr blue:bPtr alpha:NULL];
  568. }
  569. if (!done) {
  570. // The method getRed:green:blue:alpha: was only available starting iOS 5.
  571. // So in iOS 4 and earlier, we have to jump through hoops.
  572. CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
  573. unsigned char pixel[4];
  574. CGContextRef context = CGBitmapContextCreate(&pixel, 1, 1, 8, 4, rgbColorSpace, (CGBitmapInfo)(kCGBitmapAlphaInfoMask & kCGImageAlphaNoneSkipLast));
  575. CGContextSetFillColorWithColor(context, [color CGColor]);
  576. CGContextFillRect(context, CGRectMake(0, 0, 1, 1));
  577. if (rPtr) {
  578. *rPtr = pixel[0] / 255.0f;
  579. }
  580. if (gPtr) {
  581. *gPtr = pixel[1] / 255.0f;
  582. }
  583. if (bPtr) {
  584. *bPtr = pixel[2] / 255.0f;
  585. }
  586. CGContextRelease(context);
  587. CGColorSpaceRelease(rgbColorSpace);
  588. }
  589. #elif __has_include(<AppKit/NSColor.h>)
  590. // OS X with AppKit
  591. NSColor *safeColor = [color colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
  592. [safeColor getRed:rPtr green:gPtr blue:bPtr alpha:NULL];
  593. #else /* if TARGET_OS_IPHONE */
  594. // OS X without AppKit
  595. [color getRed:rPtr green:gPtr blue:bPtr alpha:NULL];
  596. #endif /* if TARGET_OS_IPHONE */
  597. }
  598. /**
  599. * Maps the given color to the closest available color supported by the shell.
  600. * The shell may support 256 colors, or only 16.
  601. *
  602. * This method loops through the known supported color set, and calculates the closest color.
  603. * The array index of that color, within the colors array, is then returned.
  604. * This array index may also be used as the index within the codes_fg and codes_bg arrays.
  605. **/
  606. + (NSUInteger)codeIndexForColor:(DDColor *)inColor {
  607. CGFloat inR, inG, inB;
  608. [self getRed:&inR green:&inG blue:&inB fromColor:inColor];
  609. NSUInteger bestIndex = 0;
  610. CGFloat lowestDistance = 100.0f;
  611. NSUInteger i = 0;
  612. for (DDColor *color in colors) {
  613. // Calculate Euclidean distance (lower value means closer to given color)
  614. CGFloat r, g, b;
  615. [self getRed:&r green:&g blue:&b fromColor:color];
  616. #if CGFLOAT_IS_DOUBLE
  617. CGFloat distance = sqrt(pow(r - inR, 2.0) + pow(g - inG, 2.0) + pow(b - inB, 2.0));
  618. #else
  619. CGFloat distance = sqrtf(powf(r - inR, 2.0f) + powf(g - inG, 2.0f) + powf(b - inB, 2.0f));
  620. #endif
  621. NSLogVerbose(@"DDTTYLogger: %3lu : %.3f,%.3f,%.3f & %.3f,%.3f,%.3f = %.6f",
  622. (unsigned long)i, inR, inG, inB, r, g, b, distance);
  623. if (distance < lowestDistance) {
  624. bestIndex = i;
  625. lowestDistance = distance;
  626. NSLogVerbose(@"DDTTYLogger: New best index = %lu", (unsigned long)bestIndex);
  627. }
  628. i++;
  629. }
  630. return bestIndex;
  631. }
  632. + (instancetype)sharedInstance {
  633. static dispatch_once_t DDTTYLoggerOnceToken;
  634. dispatch_once(&DDTTYLoggerOnceToken, ^{
  635. // Xcode does NOT natively support colors in the Xcode debugging console.
  636. // You'll need to install the XcodeColors plugin to see colors in the Xcode console.
  637. //
  638. // PS - Please read the header file before diving into the source code.
  639. char *xcode_colors = getenv("XcodeColors");
  640. char *term = getenv("TERM");
  641. if (xcode_colors && (strcmp(xcode_colors, "YES") == 0)) {
  642. isaXcodeColorTTY = YES;
  643. } else if (term) {
  644. if (strcasestr(term, "color") != NULL) {
  645. isaColorTTY = YES;
  646. isaColor256TTY = (strcasestr(term, "256") != NULL);
  647. if (isaColor256TTY) {
  648. [self initialize_colors_256];
  649. } else {
  650. [self initialize_colors_16];
  651. }
  652. }
  653. }
  654. NSLogInfo(@"DDTTYLogger: isaColorTTY = %@", (isaColorTTY ? @"YES" : @"NO"));
  655. NSLogInfo(@"DDTTYLogger: isaColor256TTY: %@", (isaColor256TTY ? @"YES" : @"NO"));
  656. NSLogInfo(@"DDTTYLogger: isaXcodeColorTTY: %@", (isaXcodeColorTTY ? @"YES" : @"NO"));
  657. sharedInstance = [[[self class] alloc] init];
  658. });
  659. return sharedInstance;
  660. }
  661. - (instancetype)init {
  662. if (sharedInstance != nil) {
  663. return nil;
  664. }
  665. if ((self = [super init])) {
  666. _calendarUnitFlags = (NSCalendarUnitYear |
  667. NSCalendarUnitMonth |
  668. NSCalendarUnitDay |
  669. NSCalendarUnitHour |
  670. NSCalendarUnitMinute |
  671. NSCalendarUnitSecond);
  672. // Initialze 'app' variable (char *)
  673. _appName = [[NSProcessInfo processInfo] processName];
  674. _appLen = [_appName lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
  675. if (_appLen == 0) {
  676. _appName = @"<UnnamedApp>";
  677. _appLen = [_appName lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
  678. }
  679. _app = (char *)malloc(_appLen + 1);
  680. if (_app == NULL) {
  681. return nil;
  682. }
  683. BOOL processedAppName = [_appName getCString:_app maxLength:(_appLen + 1) encoding:NSUTF8StringEncoding];
  684. if (NO == processedAppName) {
  685. free(_app);
  686. return nil;
  687. }
  688. // Initialize 'pid' variable (char *)
  689. _processID = [NSString stringWithFormat:@"%i", (int)getpid()];
  690. _pidLen = [_processID lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
  691. _pid = (char *)malloc(_pidLen + 1);
  692. if (_pid == NULL) {
  693. free(_app);
  694. return nil;
  695. }
  696. BOOL processedID = [_processID getCString:_pid maxLength:(_pidLen + 1) encoding:NSUTF8StringEncoding];
  697. if (NO == processedID) {
  698. free(_app);
  699. free(_pid);
  700. return nil;
  701. }
  702. // Initialize color stuff
  703. _colorsEnabled = NO;
  704. _colorProfilesArray = [[NSMutableArray alloc] initWithCapacity:8];
  705. _colorProfilesDict = [[NSMutableDictionary alloc] initWithCapacity:8];
  706. _automaticallyAppendNewlineForCustomFormatters = YES;
  707. }
  708. return self;
  709. }
  710. - (void)loadDefaultColorProfiles {
  711. [self setForegroundColor:DDMakeColor(214, 57, 30) backgroundColor:nil forFlag:DDLogFlagError];
  712. [self setForegroundColor:DDMakeColor(204, 121, 32) backgroundColor:nil forFlag:DDLogFlagWarning];
  713. }
  714. - (BOOL)colorsEnabled {
  715. // The design of this method is taken from the DDAbstractLogger implementation.
  716. // For extensive documentation please refer to the DDAbstractLogger implementation.
  717. // Note: The internal implementation MUST access the colorsEnabled variable directly,
  718. // This method is designed explicitly for external access.
  719. //
  720. // Using "self." syntax to go through this method will cause immediate deadlock.
  721. // This is the intended result. Fix it by accessing the ivar directly.
  722. // Great strides have been take to ensure this is safe to do. Plus it's MUCH faster.
  723. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  724. NSAssert(![self isOnInternalLoggerQueue], @"MUST access ivar directly, NOT via self.* syntax.");
  725. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  726. __block BOOL result;
  727. dispatch_sync(globalLoggingQueue, ^{
  728. dispatch_sync(self.loggerQueue, ^{
  729. result = _colorsEnabled;
  730. });
  731. });
  732. return result;
  733. }
  734. - (void)setColorsEnabled:(BOOL)newColorsEnabled {
  735. dispatch_block_t block = ^{
  736. @autoreleasepool {
  737. _colorsEnabled = newColorsEnabled;
  738. if ([_colorProfilesArray count] == 0) {
  739. [self loadDefaultColorProfiles];
  740. }
  741. }
  742. };
  743. // The design of this method is taken from the DDAbstractLogger implementation.
  744. // For extensive documentation please refer to the DDAbstractLogger implementation.
  745. // Note: The internal implementation MUST access the colorsEnabled variable directly,
  746. // This method is designed explicitly for external access.
  747. //
  748. // Using "self." syntax to go through this method will cause immediate deadlock.
  749. // This is the intended result. Fix it by accessing the ivar directly.
  750. // Great strides have been take to ensure this is safe to do. Plus it's MUCH faster.
  751. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  752. NSAssert(![self isOnInternalLoggerQueue], @"MUST access ivar directly, NOT via self.* syntax.");
  753. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  754. dispatch_async(globalLoggingQueue, ^{
  755. dispatch_async(self.loggerQueue, block);
  756. });
  757. }
  758. - (void)setForegroundColor:(DDColor *)txtColor backgroundColor:(DDColor *)bgColor forFlag:(DDLogFlag)mask {
  759. [self setForegroundColor:txtColor backgroundColor:bgColor forFlag:mask context:LOG_CONTEXT_ALL];
  760. }
  761. - (void)setForegroundColor:(DDColor *)txtColor backgroundColor:(DDColor *)bgColor forFlag:(DDLogFlag)mask context:(NSInteger)ctxt {
  762. dispatch_block_t block = ^{
  763. @autoreleasepool {
  764. DDTTYLoggerColorProfile *newColorProfile =
  765. [[DDTTYLoggerColorProfile alloc] initWithForegroundColor:txtColor
  766. backgroundColor:bgColor
  767. flag:mask
  768. context:ctxt];
  769. NSLogInfo(@"DDTTYLogger: newColorProfile: %@", newColorProfile);
  770. NSUInteger i = 0;
  771. for (DDTTYLoggerColorProfile *colorProfile in _colorProfilesArray) {
  772. if ((colorProfile->mask == mask) && (colorProfile->context == ctxt)) {
  773. break;
  774. }
  775. i++;
  776. }
  777. if (i < [_colorProfilesArray count]) {
  778. _colorProfilesArray[i] = newColorProfile;
  779. } else {
  780. [_colorProfilesArray addObject:newColorProfile];
  781. }
  782. }
  783. };
  784. // The design of the setter logic below is taken from the DDAbstractLogger implementation.
  785. // For documentation please refer to the DDAbstractLogger implementation.
  786. if ([self isOnInternalLoggerQueue]) {
  787. block();
  788. } else {
  789. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  790. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  791. dispatch_async(globalLoggingQueue, ^{
  792. dispatch_async(self.loggerQueue, block);
  793. });
  794. }
  795. }
  796. - (void)setForegroundColor:(DDColor *)txtColor backgroundColor:(DDColor *)bgColor forTag:(id <NSCopying>)tag {
  797. NSAssert([(id < NSObject >) tag conformsToProtocol: @protocol(NSCopying)], @"Invalid tag");
  798. dispatch_block_t block = ^{
  799. @autoreleasepool {
  800. DDTTYLoggerColorProfile *newColorProfile =
  801. [[DDTTYLoggerColorProfile alloc] initWithForegroundColor:txtColor
  802. backgroundColor:bgColor
  803. flag:(DDLogFlag)0
  804. context:0];
  805. NSLogInfo(@"DDTTYLogger: newColorProfile: %@", newColorProfile);
  806. _colorProfilesDict[tag] = newColorProfile;
  807. }
  808. };
  809. // The design of the setter logic below is taken from the DDAbstractLogger implementation.
  810. // For documentation please refer to the DDAbstractLogger implementation.
  811. if ([self isOnInternalLoggerQueue]) {
  812. block();
  813. } else {
  814. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  815. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  816. dispatch_async(globalLoggingQueue, ^{
  817. dispatch_async(self.loggerQueue, block);
  818. });
  819. }
  820. }
  821. - (void)clearColorsForFlag:(DDLogFlag)mask {
  822. [self clearColorsForFlag:mask context:0];
  823. }
  824. - (void)clearColorsForFlag:(DDLogFlag)mask context:(NSInteger)context {
  825. dispatch_block_t block = ^{
  826. @autoreleasepool {
  827. NSUInteger i = 0;
  828. for (DDTTYLoggerColorProfile *colorProfile in _colorProfilesArray) {
  829. if ((colorProfile->mask == mask) && (colorProfile->context == context)) {
  830. break;
  831. }
  832. i++;
  833. }
  834. if (i < [_colorProfilesArray count]) {
  835. [_colorProfilesArray removeObjectAtIndex:i];
  836. }
  837. }
  838. };
  839. // The design of the setter logic below is taken from the DDAbstractLogger implementation.
  840. // For documentation please refer to the DDAbstractLogger implementation.
  841. if ([self isOnInternalLoggerQueue]) {
  842. block();
  843. } else {
  844. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  845. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  846. dispatch_async(globalLoggingQueue, ^{
  847. dispatch_async(self.loggerQueue, block);
  848. });
  849. }
  850. }
  851. - (void)clearColorsForTag:(id <NSCopying>)tag {
  852. NSAssert([(id < NSObject >) tag conformsToProtocol: @protocol(NSCopying)], @"Invalid tag");
  853. dispatch_block_t block = ^{
  854. @autoreleasepool {
  855. [_colorProfilesDict removeObjectForKey:tag];
  856. }
  857. };
  858. // The design of the setter logic below is taken from the DDAbstractLogger implementation.
  859. // For documentation please refer to the DDAbstractLogger implementation.
  860. if ([self isOnInternalLoggerQueue]) {
  861. block();
  862. } else {
  863. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  864. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  865. dispatch_async(globalLoggingQueue, ^{
  866. dispatch_async(self.loggerQueue, block);
  867. });
  868. }
  869. }
  870. - (void)clearColorsForAllFlags {
  871. dispatch_block_t block = ^{
  872. @autoreleasepool {
  873. [_colorProfilesArray removeAllObjects];
  874. }
  875. };
  876. // The design of the setter logic below is taken from the DDAbstractLogger implementation.
  877. // For documentation please refer to the DDAbstractLogger implementation.
  878. if ([self isOnInternalLoggerQueue]) {
  879. block();
  880. } else {
  881. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  882. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  883. dispatch_async(globalLoggingQueue, ^{
  884. dispatch_async(self.loggerQueue, block);
  885. });
  886. }
  887. }
  888. - (void)clearColorsForAllTags {
  889. dispatch_block_t block = ^{
  890. @autoreleasepool {
  891. [_colorProfilesDict removeAllObjects];
  892. }
  893. };
  894. // The design of the setter logic below is taken from the DDAbstractLogger implementation.
  895. // For documentation please refer to the DDAbstractLogger implementation.
  896. if ([self isOnInternalLoggerQueue]) {
  897. block();
  898. } else {
  899. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  900. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  901. dispatch_async(globalLoggingQueue, ^{
  902. dispatch_async(self.loggerQueue, block);
  903. });
  904. }
  905. }
  906. - (void)clearAllColors {
  907. dispatch_block_t block = ^{
  908. @autoreleasepool {
  909. [_colorProfilesArray removeAllObjects];
  910. [_colorProfilesDict removeAllObjects];
  911. }
  912. };
  913. // The design of the setter logic below is taken from the DDAbstractLogger implementation.
  914. // For documentation please refer to the DDAbstractLogger implementation.
  915. if ([self isOnInternalLoggerQueue]) {
  916. block();
  917. } else {
  918. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  919. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  920. dispatch_async(globalLoggingQueue, ^{
  921. dispatch_async(self.loggerQueue, block);
  922. });
  923. }
  924. }
  925. - (void)logMessage:(DDLogMessage *)logMessage {
  926. NSString *logMsg = logMessage->_message;
  927. BOOL isFormatted = NO;
  928. if (_logFormatter) {
  929. logMsg = [_logFormatter formatLogMessage:logMessage];
  930. isFormatted = logMsg != logMessage->_message;
  931. }
  932. if (logMsg) {
  933. // Search for a color profile associated with the log message
  934. DDTTYLoggerColorProfile *colorProfile = nil;
  935. if (_colorsEnabled) {
  936. if (logMessage->_tag) {
  937. colorProfile = _colorProfilesDict[logMessage->_tag];
  938. }
  939. if (colorProfile == nil) {
  940. for (DDTTYLoggerColorProfile *cp in _colorProfilesArray) {
  941. if (logMessage->_flag & cp->mask) {
  942. // Color profile set for this context?
  943. if (logMessage->_context == cp->context) {
  944. colorProfile = cp;
  945. // Stop searching
  946. break;
  947. }
  948. // Check if LOG_CONTEXT_ALL was specified as a default color for this flag
  949. if (cp->context == LOG_CONTEXT_ALL) {
  950. colorProfile = cp;
  951. // We don't break to keep searching for more specific color profiles for the context
  952. }
  953. }
  954. }
  955. }
  956. }
  957. // Convert log message to C string.
  958. //
  959. // We use the stack instead of the heap for speed if possible.
  960. // But we're extra cautious to avoid a stack overflow.
  961. NSUInteger msgLen = [logMsg lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
  962. const BOOL useStack = msgLen < (1024 * 4);
  963. char msgStack[useStack ? (msgLen + 1) : 1]; // Analyzer doesn't like zero-size array, hence the 1
  964. char *msg = useStack ? msgStack : (char *)malloc(msgLen + 1);
  965. if (msg == NULL) {
  966. return;
  967. }
  968. BOOL logMsgEnc = [logMsg getCString:msg maxLength:(msgLen + 1) encoding:NSUTF8StringEncoding];
  969. if (!logMsgEnc) {
  970. if (!useStack && msg != NULL) {
  971. free(msg);
  972. }
  973. return;
  974. }
  975. // Write the log message to STDERR
  976. if (isFormatted) {
  977. // The log message has already been formatted.
  978. int iovec_len = (_automaticallyAppendNewlineForCustomFormatters) ? 5 : 4;
  979. struct iovec v[iovec_len];
  980. if (colorProfile) {
  981. v[0].iov_base = colorProfile->fgCode;
  982. v[0].iov_len = colorProfile->fgCodeLen;
  983. v[1].iov_base = colorProfile->bgCode;
  984. v[1].iov_len = colorProfile->bgCodeLen;
  985. v[iovec_len - 1].iov_base = colorProfile->resetCode;
  986. v[iovec_len - 1].iov_len = colorProfile->resetCodeLen;
  987. } else {
  988. v[0].iov_base = "";
  989. v[0].iov_len = 0;
  990. v[1].iov_base = "";
  991. v[1].iov_len = 0;
  992. v[iovec_len - 1].iov_base = "";
  993. v[iovec_len - 1].iov_len = 0;
  994. }
  995. v[2].iov_base = (char *)msg;
  996. v[2].iov_len = msgLen;
  997. if (iovec_len == 5) {
  998. v[3].iov_base = "\n";
  999. v[3].iov_len = (msg[msgLen] == '\n') ? 0 : 1;
  1000. }
  1001. writev(STDERR_FILENO, v, iovec_len);
  1002. } else {
  1003. // The log message is unformatted, so apply standard NSLog style formatting.
  1004. int len;
  1005. char ts[24] = "";
  1006. size_t tsLen = 0;
  1007. // Calculate timestamp.
  1008. // The technique below is faster than using NSDateFormatter.
  1009. if (logMessage->_timestamp) {
  1010. NSDateComponents *components = [[NSCalendar autoupdatingCurrentCalendar] components:_calendarUnitFlags fromDate:logMessage->_timestamp];
  1011. NSTimeInterval epoch = [logMessage->_timestamp timeIntervalSinceReferenceDate];
  1012. int milliseconds = (int)((epoch - floor(epoch)) * 1000);
  1013. len = snprintf(ts, 24, "%04ld-%02ld-%02ld %02ld:%02ld:%02ld:%03d", // yyyy-MM-dd HH:mm:ss:SSS
  1014. (long)components.year,
  1015. (long)components.month,
  1016. (long)components.day,
  1017. (long)components.hour,
  1018. (long)components.minute,
  1019. (long)components.second, milliseconds);
  1020. tsLen = (NSUInteger)MAX(MIN(24 - 1, len), 0);
  1021. }
  1022. // Calculate thread ID
  1023. //
  1024. // How many characters do we need for the thread id?
  1025. // logMessage->machThreadID is of type mach_port_t, which is an unsigned int.
  1026. //
  1027. // 1 hex char = 4 bits
  1028. // 8 hex chars for 32 bit, plus ending '\0' = 9
  1029. char tid[9];
  1030. len = snprintf(tid, 9, "%s", [logMessage->_threadID cStringUsingEncoding:NSUTF8StringEncoding]);
  1031. size_t tidLen = (NSUInteger)MAX(MIN(9 - 1, len), 0);
  1032. // Here is our format: "%s %s[%i:%s] %s", timestamp, appName, processID, threadID, logMsg
  1033. struct iovec v[13];
  1034. if (colorProfile) {
  1035. v[0].iov_base = colorProfile->fgCode;
  1036. v[0].iov_len = colorProfile->fgCodeLen;
  1037. v[1].iov_base = colorProfile->bgCode;
  1038. v[1].iov_len = colorProfile->bgCodeLen;
  1039. v[12].iov_base = colorProfile->resetCode;
  1040. v[12].iov_len = colorProfile->resetCodeLen;
  1041. } else {
  1042. v[0].iov_base = "";
  1043. v[0].iov_len = 0;
  1044. v[1].iov_base = "";
  1045. v[1].iov_len = 0;
  1046. v[12].iov_base = "";
  1047. v[12].iov_len = 0;
  1048. }
  1049. v[2].iov_base = ts;
  1050. v[2].iov_len = tsLen;
  1051. v[3].iov_base = " ";
  1052. v[3].iov_len = 1;
  1053. v[4].iov_base = _app;
  1054. v[4].iov_len = _appLen;
  1055. v[5].iov_base = "[";
  1056. v[5].iov_len = 1;
  1057. v[6].iov_base = _pid;
  1058. v[6].iov_len = _pidLen;
  1059. v[7].iov_base = ":";
  1060. v[7].iov_len = 1;
  1061. v[8].iov_base = tid;
  1062. v[8].iov_len = MIN((size_t)8, tidLen); // snprintf doesn't return what you might think
  1063. v[9].iov_base = "] ";
  1064. v[9].iov_len = 2;
  1065. v[10].iov_base = (char *)msg;
  1066. v[10].iov_len = msgLen;
  1067. v[11].iov_base = "\n";
  1068. v[11].iov_len = (msg[msgLen] == '\n') ? 0 : 1;
  1069. writev(STDERR_FILENO, v, 13);
  1070. }
  1071. if (!useStack) {
  1072. free(msg);
  1073. }
  1074. }
  1075. }
  1076. - (NSString *)loggerName {
  1077. return @"cocoa.lumberjack.ttyLogger";
  1078. }
  1079. @end
  1080. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1081. @implementation DDTTYLoggerColorProfile
  1082. - (instancetype)initWithForegroundColor:(DDColor *)fgColor backgroundColor:(DDColor *)bgColor flag:(DDLogFlag)aMask context:(NSInteger)ctxt {
  1083. if ((self = [super init])) {
  1084. mask = aMask;
  1085. context = ctxt;
  1086. CGFloat r, g, b;
  1087. if (fgColor) {
  1088. [DDTTYLogger getRed:&r green:&g blue:&b fromColor:fgColor];
  1089. fg_r = (uint8_t)(r * 255.0f);
  1090. fg_g = (uint8_t)(g * 255.0f);
  1091. fg_b = (uint8_t)(b * 255.0f);
  1092. }
  1093. if (bgColor) {
  1094. [DDTTYLogger getRed:&r green:&g blue:&b fromColor:bgColor];
  1095. bg_r = (uint8_t)(r * 255.0f);
  1096. bg_g = (uint8_t)(g * 255.0f);
  1097. bg_b = (uint8_t)(b * 255.0f);
  1098. }
  1099. if (fgColor && isaColorTTY) {
  1100. // Map foreground color to closest available shell color
  1101. fgCodeIndex = [DDTTYLogger codeIndexForColor:fgColor];
  1102. fgCodeRaw = codes_fg[fgCodeIndex];
  1103. NSString *escapeSeq = @"\033[";
  1104. NSUInteger len1 = [escapeSeq lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
  1105. NSUInteger len2 = [fgCodeRaw lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
  1106. BOOL escapeSeqEnc = [escapeSeq getCString:(fgCode) maxLength:(len1 + 1) encoding:NSUTF8StringEncoding];
  1107. BOOL fgCodeRawEsc = [fgCodeRaw getCString:(fgCode + len1) maxLength:(len2 + 1) encoding:NSUTF8StringEncoding];
  1108. if (!escapeSeqEnc || !fgCodeRawEsc) {
  1109. return nil;
  1110. }
  1111. fgCodeLen = len1 + len2;
  1112. } else if (fgColor && isaXcodeColorTTY) {
  1113. // Convert foreground color to color code sequence
  1114. const char *escapeSeq = XCODE_COLORS_ESCAPE_SEQ;
  1115. int result = snprintf(fgCode, 24, "%sfg%u,%u,%u;", escapeSeq, fg_r, fg_g, fg_b);
  1116. fgCodeLen = (NSUInteger)MAX(MIN(result, (24 - 1)), 0);
  1117. } else {
  1118. // No foreground color or no color support
  1119. fgCode[0] = '\0';
  1120. fgCodeLen = 0;
  1121. }
  1122. if (bgColor && isaColorTTY) {
  1123. // Map background color to closest available shell color
  1124. bgCodeIndex = [DDTTYLogger codeIndexForColor:bgColor];
  1125. bgCodeRaw = codes_bg[bgCodeIndex];
  1126. NSString *escapeSeq = @"\033[";
  1127. NSUInteger len1 = [escapeSeq lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
  1128. NSUInteger len2 = [bgCodeRaw lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
  1129. BOOL escapeSeqEnc = [escapeSeq getCString:(bgCode) maxLength:(len1 + 1) encoding:NSUTF8StringEncoding];
  1130. BOOL bgCodeRawEsc = [bgCodeRaw getCString:(bgCode + len1) maxLength:(len2 + 1) encoding:NSUTF8StringEncoding];
  1131. if (!escapeSeqEnc || !bgCodeRawEsc) {
  1132. return nil;
  1133. }
  1134. bgCodeLen = len1 + len2;
  1135. } else if (bgColor && isaXcodeColorTTY) {
  1136. // Convert background color to color code sequence
  1137. const char *escapeSeq = XCODE_COLORS_ESCAPE_SEQ;
  1138. int result = snprintf(bgCode, 24, "%sbg%u,%u,%u;", escapeSeq, bg_r, bg_g, bg_b);
  1139. bgCodeLen = (NSUInteger)MAX(MIN(result, (24 - 1)), 0);
  1140. } else {
  1141. // No background color or no color support
  1142. bgCode[0] = '\0';
  1143. bgCodeLen = 0;
  1144. }
  1145. if (isaColorTTY) {
  1146. resetCodeLen = (NSUInteger)MAX(snprintf(resetCode, 8, "\033[0m"), 0);
  1147. } else if (isaXcodeColorTTY) {
  1148. resetCodeLen = (NSUInteger)MAX(snprintf(resetCode, 8, XCODE_COLORS_RESET), 0);
  1149. } else {
  1150. resetCode[0] = '\0';
  1151. resetCodeLen = 0;
  1152. }
  1153. }
  1154. return self;
  1155. }
  1156. - (NSString *)description {
  1157. return [NSString stringWithFormat:
  1158. @"<DDTTYLoggerColorProfile: %p mask:%i ctxt:%ld fg:%u,%u,%u bg:%u,%u,%u fgCode:%@ bgCode:%@>",
  1159. self, (int)mask, (long)context, fg_r, fg_g, fg_b, bg_r, bg_g, bg_b, fgCodeRaw, bgCodeRaw];
  1160. }
  1161. @end