The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

487 lines
16KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-11 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. #include "../jucer_Headers.h"
  19. #include "jucer_CodeHelpers.h"
  20. //==============================================================================
  21. namespace CodeHelpers
  22. {
  23. String indent (const String& code, const int numSpaces, bool indentFirstLine)
  24. {
  25. if (numSpaces == 0)
  26. return code;
  27. const String space (String::repeatedString (" ", numSpaces));
  28. StringArray lines;
  29. lines.addLines (code);
  30. for (int i = (indentFirstLine ? 0 : 1); i < lines.size(); ++i)
  31. {
  32. String s (lines[i].trimEnd());
  33. if (s.isNotEmpty())
  34. s = space + s;
  35. lines.set (i, s);
  36. }
  37. return lines.joinIntoString (newLine);
  38. }
  39. String makeValidIdentifier (String s, bool capitalise, bool removeColons, bool allowTemplates)
  40. {
  41. if (s.isEmpty())
  42. return "unknown";
  43. if (removeColons)
  44. s = s.replaceCharacters (".,;:/@", "______");
  45. else
  46. s = s.replaceCharacters (".,;/@", "_____");
  47. int i;
  48. for (i = s.length(); --i > 0;)
  49. if (CharacterFunctions::isLetter (s[i])
  50. && CharacterFunctions::isLetter (s[i - 1])
  51. && CharacterFunctions::isUpperCase (s[i])
  52. && ! CharacterFunctions::isUpperCase (s[i - 1]))
  53. s = s.substring (0, i) + " " + s.substring (i);
  54. String allowedChars ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_ 0123456789");
  55. if (allowTemplates)
  56. allowedChars += "<>";
  57. if (! removeColons)
  58. allowedChars += ":";
  59. StringArray words;
  60. words.addTokens (s.retainCharacters (allowedChars), false);
  61. words.trim();
  62. String n (words[0]);
  63. if (capitalise)
  64. n = n.toLowerCase();
  65. for (i = 1; i < words.size(); ++i)
  66. {
  67. if (capitalise && words[i].length() > 1)
  68. n << words[i].substring (0, 1).toUpperCase()
  69. << words[i].substring (1).toLowerCase();
  70. else
  71. n << words[i];
  72. }
  73. if (CharacterFunctions::isDigit (n[0]))
  74. n = "_" + n;
  75. if (CPlusPlusCodeTokeniser::isReservedKeyword (n))
  76. n << '_';
  77. return n;
  78. }
  79. static void writeEscapeChars (OutputStream& out, const char* utf8, const int numBytes,
  80. const int maxCharsOnLine, const bool breakAtNewLines,
  81. const bool replaceSingleQuotes, const bool allowStringBreaks)
  82. {
  83. int charsOnLine = 0;
  84. bool lastWasHexEscapeCode = false;
  85. for (int i = 0; i < numBytes || numBytes < 0; ++i)
  86. {
  87. const unsigned char c = (unsigned char) utf8[i];
  88. bool startNewLine = false;
  89. switch (c)
  90. {
  91. case '\t': out << "\\t"; lastWasHexEscapeCode = false; charsOnLine += 2; break;
  92. case '\r': out << "\\r"; lastWasHexEscapeCode = false; charsOnLine += 2; break;
  93. case '\n': out << "\\n"; lastWasHexEscapeCode = false; charsOnLine += 2; startNewLine = breakAtNewLines; break;
  94. case '\\': out << "\\\\"; lastWasHexEscapeCode = false; charsOnLine += 2; break;
  95. case '\"': out << "\\\""; lastWasHexEscapeCode = false; charsOnLine += 2; break;
  96. case 0:
  97. if (numBytes < 0)
  98. return;
  99. out << "\\0";
  100. lastWasHexEscapeCode = true;
  101. charsOnLine += 2;
  102. break;
  103. case '\'':
  104. if (replaceSingleQuotes)
  105. {
  106. out << "\\\'";
  107. lastWasHexEscapeCode = false;
  108. charsOnLine += 2;
  109. break;
  110. }
  111. // deliberate fall-through...
  112. default:
  113. if (c >= 32 && c < 127 && ! (lastWasHexEscapeCode // (have to avoid following a hex escape sequence with a valid hex digit)
  114. && CharacterFunctions::getHexDigitValue (c) >= 0))
  115. {
  116. out << (char) c;
  117. lastWasHexEscapeCode = false;
  118. ++charsOnLine;
  119. }
  120. else if (allowStringBreaks && lastWasHexEscapeCode && c >= 32 && c < 127)
  121. {
  122. out << "\"\"" << (char) c;
  123. lastWasHexEscapeCode = false;
  124. charsOnLine += 3;
  125. }
  126. else
  127. {
  128. out << (c < 16 ? "\\x0" : "\\x") << String::toHexString ((int) c);
  129. lastWasHexEscapeCode = true;
  130. charsOnLine += 4;
  131. }
  132. break;
  133. }
  134. if ((startNewLine || (maxCharsOnLine > 0 && charsOnLine >= maxCharsOnLine))
  135. && (numBytes < 0 || i < numBytes - 1))
  136. {
  137. charsOnLine = 0;
  138. out << "\"" << newLine << "\"";
  139. lastWasHexEscapeCode = false;
  140. }
  141. }
  142. }
  143. String addEscapeChars (const String& s)
  144. {
  145. MemoryOutputStream out;
  146. writeEscapeChars (out, s.toUTF8().getAddress(), -1, -1, false, true, true);
  147. return out.toUTF8();
  148. }
  149. String createIncludeStatement (const File& includeFile, const File& targetFile)
  150. {
  151. return createIncludeStatement (FileHelpers::unixStylePath (includeFile.getRelativePathFrom (targetFile.getParentDirectory())));
  152. }
  153. String createIncludeStatement (const String& includePath)
  154. {
  155. if (includePath.startsWithChar ('<') || includePath.startsWithChar ('"'))
  156. return "#include " + includePath;
  157. else
  158. return "#include \"" + includePath + "\"";
  159. }
  160. String makeHeaderGuardName (const File& file)
  161. {
  162. return "__" + file.getFileName().toUpperCase()
  163. .replaceCharacters (" .", "__")
  164. .retainCharacters ("_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
  165. + "_" + String::toHexString (file.hashCode()).toUpperCase() + "__";
  166. }
  167. String makeBinaryDataIdentifierName (const File& file)
  168. {
  169. return makeValidIdentifier (file.getFileName()
  170. .replaceCharacters (" .", "__")
  171. .retainCharacters ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_0123456789"),
  172. false, true, false);
  173. }
  174. String stringLiteral (const String& text)
  175. {
  176. if (text.isEmpty())
  177. return "String::empty";
  178. if (CharPointer_ASCII::isValidString (text.toUTF8(), std::numeric_limits<int>::max()))
  179. return CodeHelpers::addEscapeChars (text).quoted();
  180. else
  181. return "CharPointer_UTF8 (" + CodeHelpers::addEscapeChars (text).quoted() + ")";
  182. }
  183. String stringLiteralIfNotEmpty (const String& text)
  184. {
  185. return text.isNotEmpty() ? stringLiteral (text) : String::empty;
  186. }
  187. String boolLiteral (const bool b)
  188. {
  189. return b ? "true" : "false";
  190. }
  191. String floatLiteral (float v)
  192. {
  193. String s ((double) v, 4);
  194. if (s.containsChar ('.'))
  195. {
  196. s = s.trimCharactersAtEnd ("0");
  197. if (s.endsWithChar ('.'))
  198. s << '0';
  199. s << 'f';
  200. }
  201. else
  202. {
  203. s << ".0f";
  204. }
  205. return s;
  206. }
  207. String doubleLiteral (double v)
  208. {
  209. String s (v, 7);
  210. if (s.containsChar ('.'))
  211. {
  212. s = s.trimCharactersAtEnd ("0");
  213. if (s.endsWithChar ('.'))
  214. s << '0';
  215. }
  216. else
  217. {
  218. s << ".0";
  219. }
  220. return s;
  221. }
  222. String alignFunctionCallParams (const String& call, const StringArray& parameters, const int maxLineLength)
  223. {
  224. String result, currentLine (call);
  225. for (int i = 0; i < parameters.size(); ++i)
  226. {
  227. if (currentLine.length() >= maxLineLength)
  228. {
  229. result += currentLine.trimEnd() + newLine;
  230. currentLine = String::repeatedString (" ", call.length()) + parameters[i];
  231. }
  232. else
  233. {
  234. currentLine += parameters[i];
  235. }
  236. if (i < parameters.size() - 1)
  237. currentLine << ", ";
  238. }
  239. return result + currentLine.trimEnd() + ")";
  240. }
  241. String colourToCode (const Colour& col)
  242. {
  243. const Colour colours[] =
  244. {
  245. #define COL(col) Colours::col,
  246. #include "jucer_Colours.h"
  247. #undef COL
  248. Colours::transparentBlack
  249. };
  250. static const char* colourNames[] =
  251. {
  252. #define COL(col) #col,
  253. #include "jucer_Colours.h"
  254. #undef COL
  255. 0
  256. };
  257. for (int i = 0; i < numElementsInArray (colourNames) - 1; ++i)
  258. if (col == colours[i])
  259. return "Colours::" + String (colourNames[i]);
  260. return "Colour (0x" + hexString8Digits ((int) col.getARGB()) + ')';
  261. }
  262. String castToFloat (const String& expression)
  263. {
  264. if (expression.containsOnly ("0123456789.f"))
  265. {
  266. String s (expression.getFloatValue());
  267. if (s.containsChar ('.'))
  268. return s + "f";
  269. return s + ".0f";
  270. }
  271. return "(float) (" + expression + ")";
  272. }
  273. String castToInt (const String& expression)
  274. {
  275. if (expression.containsOnly ("0123456789."))
  276. return String ((int) expression.getFloatValue());
  277. return "(int) (" + expression + ")";
  278. }
  279. void writeDataAsCppLiteral (const MemoryBlock& mb, OutputStream& out,
  280. bool breakAtNewLines, bool allowStringBreaks)
  281. {
  282. const int maxCharsOnLine = 250;
  283. const unsigned char* data = (const unsigned char*) mb.getData();
  284. int charsOnLine = 0;
  285. bool canUseStringLiteral = mb.getSize() < 32768; // MS compilers can't handle big string literals..
  286. if (canUseStringLiteral)
  287. {
  288. unsigned int numEscaped = 0;
  289. for (size_t i = 0; i < mb.getSize(); ++i)
  290. {
  291. const unsigned int num = (unsigned int) data[i];
  292. if (! ((num >= 32 && num < 127) || num == '\t' || num == '\r' || num == '\n'))
  293. {
  294. if (++numEscaped > mb.getSize() / 4)
  295. {
  296. canUseStringLiteral = false;
  297. break;
  298. }
  299. }
  300. }
  301. }
  302. if (! canUseStringLiteral)
  303. {
  304. out << "{ ";
  305. for (size_t i = 0; i < mb.getSize(); ++i)
  306. {
  307. const int num = (int) (unsigned int) data[i];
  308. out << num << ',';
  309. charsOnLine += 2;
  310. if (num >= 10)
  311. ++charsOnLine;
  312. if (num >= 100)
  313. ++charsOnLine;
  314. if (charsOnLine >= maxCharsOnLine)
  315. {
  316. charsOnLine = 0;
  317. out << newLine;
  318. }
  319. }
  320. out << "0,0 };";
  321. }
  322. else
  323. {
  324. out << "\"";
  325. writeEscapeChars (out, (const char*) data, (int) mb.getSize(),
  326. maxCharsOnLine, breakAtNewLines, false, allowStringBreaks);
  327. out << "\";";
  328. }
  329. }
  330. static int calculateHash (const String& s, const int hashMultiplier)
  331. {
  332. const char* t = s.toUTF8();
  333. int hash = 0;
  334. while (*t != 0)
  335. hash = hashMultiplier * hash + *t++;
  336. return hash;
  337. }
  338. static int findBestHashMultiplier (const StringArray& strings)
  339. {
  340. StringArray allStrings;
  341. for (int i = strings.size(); --i >= 0;)
  342. allStrings.addTokens (strings[i], "|", "");
  343. int v = 31;
  344. for (;;)
  345. {
  346. SortedSet <int> hashes;
  347. bool collision = false;
  348. for (int i = allStrings.size(); --i >= 0;)
  349. {
  350. const int hash = calculateHash (allStrings[i], v);
  351. if (hashes.contains (hash))
  352. {
  353. collision = true;
  354. break;
  355. }
  356. hashes.add (hash);
  357. }
  358. if (! collision)
  359. break;
  360. v += 2;
  361. }
  362. return v;
  363. }
  364. void createStringMatcher (OutputStream& out, const String& utf8PointerVariable,
  365. const StringArray& strings, const StringArray& codeToExecute, const int indentLevel)
  366. {
  367. jassert (strings.size() == codeToExecute.size());
  368. const String indent (String::repeatedString (" ", indentLevel));
  369. const int hashMultiplier = findBestHashMultiplier (strings);
  370. out << indent << "int hash = 0;" << newLine
  371. << indent << "if (" << utf8PointerVariable << " != 0)" << newLine
  372. << indent << " while (*" << utf8PointerVariable << " != 0)" << newLine
  373. << indent << " hash = " << hashMultiplier << " * hash + *" << utf8PointerVariable << "++;" << newLine
  374. << newLine
  375. << indent << "switch (hash)" << newLine
  376. << indent << "{" << newLine;
  377. for (int i = 0; i < strings.size(); ++i)
  378. {
  379. StringArray matchingStrings;
  380. matchingStrings.addTokens (strings[i], "|", "");
  381. for (int j = 0; j < matchingStrings.size(); ++j)
  382. {
  383. out << indent << " case 0x" << hexString8Digits (calculateHash (matchingStrings[j], hashMultiplier)) << ":";
  384. if (j < matchingStrings.size() - 1)
  385. out << newLine;
  386. }
  387. out << " " << codeToExecute[i] << newLine;
  388. }
  389. out << indent << " default: break;" << newLine
  390. << indent << "}" << newLine << newLine;
  391. }
  392. }