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.

473 lines
15KB

  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, const bool replaceSingleQuotes)
  81. {
  82. int charsOnLine = 0;
  83. bool lastWasHexEscapeCode = false;
  84. for (int i = 0; i < numBytes || numBytes < 0; ++i)
  85. {
  86. const unsigned char c = (unsigned char) utf8[i];
  87. bool startNewLine = false;
  88. switch (c)
  89. {
  90. case '\t': out << "\\t"; lastWasHexEscapeCode = false; break;
  91. case '\r': out << "\\r"; lastWasHexEscapeCode = false; break;
  92. case '\n': out << "\\n"; lastWasHexEscapeCode = false; startNewLine = breakAtNewLines; break;
  93. case '\\': out << "\\\\"; lastWasHexEscapeCode = false; break;
  94. case '\"': out << "\\\""; lastWasHexEscapeCode = false; break;
  95. case 0:
  96. if (numBytes < 0)
  97. return;
  98. out << "\\0";
  99. lastWasHexEscapeCode = true;
  100. break;
  101. case '\'':
  102. if (replaceSingleQuotes)
  103. {
  104. out << "\\\'";
  105. lastWasHexEscapeCode = false;
  106. break;
  107. }
  108. // deliberate fall-through...
  109. default:
  110. if (c >= 32 && c < 127 && ! (lastWasHexEscapeCode // (have to avoid following a hex escape sequence with a valid hex digit)
  111. && CharacterFunctions::getHexDigitValue (c) >= 0))
  112. {
  113. out << (char) c;
  114. lastWasHexEscapeCode = false;
  115. }
  116. else
  117. {
  118. out << (c < 16 ? "\\x0" : "\\x") << String::toHexString ((int) c);
  119. lastWasHexEscapeCode = true;
  120. }
  121. break;
  122. }
  123. if ((startNewLine || (maxCharsOnLine > 0 && ++charsOnLine >= maxCharsOnLine))
  124. && (numBytes < 0 || i < numBytes - 1))
  125. {
  126. charsOnLine = 0;
  127. out << "\"" << newLine << "\"";
  128. }
  129. }
  130. }
  131. String addEscapeChars (const String& s)
  132. {
  133. MemoryOutputStream out;
  134. writeEscapeChars (out, s.toUTF8().getAddress(), -1, -1, false, true);
  135. return out.toUTF8();
  136. }
  137. String createIncludeStatement (const File& includeFile, const File& targetFile)
  138. {
  139. return createIncludeStatement (FileHelpers::unixStylePath (includeFile.getRelativePathFrom (targetFile.getParentDirectory())));
  140. }
  141. String createIncludeStatement (const String& includePath)
  142. {
  143. if (includePath.startsWithChar ('<') || includePath.startsWithChar ('"'))
  144. return "#include " + includePath;
  145. else
  146. return "#include \"" + includePath + "\"";
  147. }
  148. String makeHeaderGuardName (const File& file)
  149. {
  150. return "__" + file.getFileName().toUpperCase()
  151. .replaceCharacters (" .", "__")
  152. .retainCharacters ("_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
  153. + "_" + String::toHexString (file.hashCode()).toUpperCase() + "__";
  154. }
  155. String makeBinaryDataIdentifierName (const File& file)
  156. {
  157. return makeValidIdentifier (file.getFileName()
  158. .replaceCharacters (" .", "__")
  159. .retainCharacters ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_0123456789"),
  160. false, true, false);
  161. }
  162. String stringLiteral (const String& text)
  163. {
  164. if (text.isEmpty())
  165. return "String::empty";
  166. if (CharPointer_ASCII::isValidString (text.toUTF8(), std::numeric_limits<int>::max()))
  167. return CodeHelpers::addEscapeChars (text).quoted();
  168. else
  169. return "CharPointer_UTF8 (" + CodeHelpers::addEscapeChars (text).quoted() + ")";
  170. }
  171. String stringLiteralIfNotEmpty (const String& text)
  172. {
  173. return text.isNotEmpty() ? stringLiteral (text) : String::empty;
  174. }
  175. String boolLiteral (const bool b)
  176. {
  177. return b ? "true" : "false";
  178. }
  179. String floatLiteral (float v)
  180. {
  181. String s ((double) v, 4);
  182. if (s.containsChar ('.'))
  183. {
  184. s = s.trimCharactersAtEnd ("0");
  185. if (s.endsWithChar ('.'))
  186. s << '0';
  187. s << 'f';
  188. }
  189. else
  190. {
  191. s << ".0f";
  192. }
  193. return s;
  194. }
  195. String doubleLiteral (double v)
  196. {
  197. String s (v, 7);
  198. if (s.containsChar ('.'))
  199. {
  200. s = s.trimCharactersAtEnd ("0");
  201. if (s.endsWithChar ('.'))
  202. s << '0';
  203. }
  204. else
  205. {
  206. s << ".0";
  207. }
  208. return s;
  209. }
  210. String alignFunctionCallParams (const String& call, const StringArray& parameters, const int maxLineLength)
  211. {
  212. String result, currentLine (call);
  213. for (int i = 0; i < parameters.size(); ++i)
  214. {
  215. if (currentLine.length() >= maxLineLength)
  216. {
  217. result += currentLine.trimEnd() + newLine;
  218. currentLine = String::repeatedString (" ", call.length()) + parameters[i];
  219. }
  220. else
  221. {
  222. currentLine += parameters[i];
  223. }
  224. if (i < parameters.size() - 1)
  225. currentLine << ", ";
  226. }
  227. return result + currentLine.trimEnd() + ")";
  228. }
  229. String colourToCode (const Colour& col)
  230. {
  231. const Colour colours[] =
  232. {
  233. #define COL(col) Colours::col,
  234. #include "jucer_Colours.h"
  235. #undef COL
  236. Colours::transparentBlack
  237. };
  238. static const char* colourNames[] =
  239. {
  240. #define COL(col) #col,
  241. #include "jucer_Colours.h"
  242. #undef COL
  243. 0
  244. };
  245. for (int i = 0; i < numElementsInArray (colourNames) - 1; ++i)
  246. if (col == colours[i])
  247. return "Colours::" + String (colourNames[i]);
  248. return "Colour (0x" + hexString8Digits ((int) col.getARGB()) + ')';
  249. }
  250. String castToFloat (const String& expression)
  251. {
  252. if (expression.containsOnly ("0123456789.f"))
  253. {
  254. String s (expression.getFloatValue());
  255. if (s.containsChar ('.'))
  256. return s + "f";
  257. return s + ".0f";
  258. }
  259. return "(float) (" + expression + ")";
  260. }
  261. String castToInt (const String& expression)
  262. {
  263. if (expression.containsOnly ("0123456789."))
  264. return String ((int) expression.getFloatValue());
  265. return "(int) (" + expression + ")";
  266. }
  267. void writeDataAsCppLiteral (const MemoryBlock& mb, OutputStream& out)
  268. {
  269. const int maxCharsOnLine = 250;
  270. const unsigned char* data = (const unsigned char*) mb.getData();
  271. int charsOnLine = 0;
  272. bool canUseStringLiteral = mb.getSize() < 32768; // MS compilers can't handle big string literals..
  273. if (canUseStringLiteral)
  274. {
  275. unsigned int numEscaped = 0;
  276. for (size_t i = 0; i < mb.getSize(); ++i)
  277. {
  278. const unsigned int num = (unsigned int) data[i];
  279. if (! ((num >= 32 && num < 127) || num == '\t' || num == '\r' || num == '\n'))
  280. {
  281. if (++numEscaped > mb.getSize() / 4)
  282. {
  283. canUseStringLiteral = false;
  284. break;
  285. }
  286. }
  287. }
  288. }
  289. if (! canUseStringLiteral)
  290. {
  291. out << "{ ";
  292. for (size_t i = 0; i < mb.getSize(); ++i)
  293. {
  294. const int num = (int) (unsigned int) data[i];
  295. out << num << ',';
  296. charsOnLine += 2;
  297. if (num >= 10)
  298. ++charsOnLine;
  299. if (num >= 100)
  300. ++charsOnLine;
  301. if (charsOnLine >= maxCharsOnLine)
  302. {
  303. charsOnLine = 0;
  304. out << newLine;
  305. }
  306. }
  307. out << "0,0 };";
  308. }
  309. else
  310. {
  311. out << "\"";
  312. writeEscapeChars (out, (const char*) data, (int) mb.getSize(), maxCharsOnLine, true, false);
  313. out << "\";";
  314. }
  315. }
  316. static int calculateHash (const String& s, const int hashMultiplier)
  317. {
  318. const char* t = s.toUTF8();
  319. int hash = 0;
  320. while (*t != 0)
  321. hash = hashMultiplier * hash + *t++;
  322. return hash;
  323. }
  324. static int findBestHashMultiplier (const StringArray& strings)
  325. {
  326. StringArray allStrings;
  327. for (int i = strings.size(); --i >= 0;)
  328. allStrings.addTokens (strings[i], "|", "");
  329. int v = 31;
  330. for (;;)
  331. {
  332. SortedSet <int> hashes;
  333. bool collision = false;
  334. for (int i = allStrings.size(); --i >= 0;)
  335. {
  336. const int hash = calculateHash (allStrings[i], v);
  337. if (hashes.contains (hash))
  338. {
  339. collision = true;
  340. break;
  341. }
  342. hashes.add (hash);
  343. }
  344. if (! collision)
  345. break;
  346. v += 2;
  347. }
  348. return v;
  349. }
  350. void createStringMatcher (OutputStream& out, const String& utf8PointerVariable,
  351. const StringArray& strings, const StringArray& codeToExecute, const int indentLevel)
  352. {
  353. jassert (strings.size() == codeToExecute.size());
  354. const String indent (String::repeatedString (" ", indentLevel));
  355. const int hashMultiplier = findBestHashMultiplier (strings);
  356. out << indent << "int hash = 0;" << newLine
  357. << indent << "if (" << utf8PointerVariable << " != 0)" << newLine
  358. << indent << " while (*" << utf8PointerVariable << " != 0)" << newLine
  359. << indent << " hash = " << hashMultiplier << " * hash + *" << utf8PointerVariable << "++;" << newLine
  360. << newLine
  361. << indent << "switch (hash)" << newLine
  362. << indent << "{" << newLine;
  363. for (int i = 0; i < strings.size(); ++i)
  364. {
  365. StringArray matchingStrings;
  366. matchingStrings.addTokens (strings[i], "|", "");
  367. for (int j = 0; j < matchingStrings.size(); ++j)
  368. {
  369. out << indent << " case 0x" << hexString8Digits (calculateHash (matchingStrings[j], hashMultiplier)) << ":";
  370. if (j < matchingStrings.size() - 1)
  371. out << newLine;
  372. }
  373. out << " " << codeToExecute[i] << newLine;
  374. }
  375. out << indent << " default: break;" << newLine
  376. << indent << "}" << newLine << newLine;
  377. }
  378. }