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.

421 lines
14KB

  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 (FileHelpers::getRelativePathFrom (includeFile, 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 alignFunctionCallParams (const String& call, const StringArray& parameters, const int maxLineLength)
  184. {
  185. String result, currentLine (call);
  186. for (int i = 0; i < parameters.size(); ++i)
  187. {
  188. if (currentLine.length() >= maxLineLength)
  189. {
  190. result += currentLine.trimEnd() + newLine;
  191. currentLine = String::repeatedString (" ", call.length()) + parameters[i];
  192. }
  193. else
  194. {
  195. currentLine += parameters[i];
  196. }
  197. if (i < parameters.size() - 1)
  198. currentLine << ", ";
  199. }
  200. return result + currentLine.trimEnd() + ")";
  201. }
  202. String colourToCode (const Colour& col)
  203. {
  204. const Colour colours[] =
  205. {
  206. #define COL(col) Colours::col,
  207. #include "jucer_Colours.h"
  208. #undef COL
  209. Colours::transparentBlack
  210. };
  211. static const char* colourNames[] =
  212. {
  213. #define COL(col) #col,
  214. #include "jucer_Colours.h"
  215. #undef COL
  216. 0
  217. };
  218. for (int i = 0; i < numElementsInArray (colourNames) - 1; ++i)
  219. if (col == colours[i])
  220. return "Colours::" + String (colourNames[i]);
  221. return "Colour (0x" + hexString8Digits ((int) col.getARGB()) + ')';
  222. }
  223. void writeDataAsCppLiteral (const MemoryBlock& mb, OutputStream& out,
  224. bool breakAtNewLines, bool allowStringBreaks)
  225. {
  226. const int maxCharsOnLine = 250;
  227. const unsigned char* data = (const unsigned char*) mb.getData();
  228. int charsOnLine = 0;
  229. bool canUseStringLiteral = mb.getSize() < 32768; // MS compilers can't handle big string literals..
  230. if (canUseStringLiteral)
  231. {
  232. unsigned int numEscaped = 0;
  233. for (size_t i = 0; i < mb.getSize(); ++i)
  234. {
  235. const unsigned int num = (unsigned int) data[i];
  236. if (! ((num >= 32 && num < 127) || num == '\t' || num == '\r' || num == '\n'))
  237. {
  238. if (++numEscaped > mb.getSize() / 4)
  239. {
  240. canUseStringLiteral = false;
  241. break;
  242. }
  243. }
  244. }
  245. }
  246. if (! canUseStringLiteral)
  247. {
  248. out << "{ ";
  249. for (size_t i = 0; i < mb.getSize(); ++i)
  250. {
  251. const int num = (int) (unsigned int) data[i];
  252. out << num << ',';
  253. charsOnLine += 2;
  254. if (num >= 10)
  255. {
  256. ++charsOnLine;
  257. if (num >= 100)
  258. ++charsOnLine;
  259. }
  260. if (charsOnLine >= maxCharsOnLine)
  261. {
  262. charsOnLine = 0;
  263. out << newLine;
  264. }
  265. }
  266. out << "0,0 };";
  267. }
  268. else
  269. {
  270. out << "\"";
  271. writeEscapeChars (out, (const char*) data, (int) mb.getSize(),
  272. maxCharsOnLine, breakAtNewLines, false, allowStringBreaks);
  273. out << "\";";
  274. }
  275. }
  276. //==============================================================================
  277. static int calculateHash (const String& s, const int hashMultiplier)
  278. {
  279. const char* t = s.toUTF8();
  280. int hash = 0;
  281. while (*t != 0)
  282. hash = hashMultiplier * hash + *t++;
  283. return hash;
  284. }
  285. static int findBestHashMultiplier (const StringArray& strings)
  286. {
  287. StringArray allStrings;
  288. for (int i = strings.size(); --i >= 0;)
  289. allStrings.addTokens (strings[i], "|", "");
  290. int v = 31;
  291. for (;;)
  292. {
  293. SortedSet <int> hashes;
  294. bool collision = false;
  295. for (int i = allStrings.size(); --i >= 0;)
  296. {
  297. const int hash = calculateHash (allStrings[i], v);
  298. if (hashes.contains (hash))
  299. {
  300. collision = true;
  301. break;
  302. }
  303. hashes.add (hash);
  304. }
  305. if (! collision)
  306. break;
  307. v += 2;
  308. }
  309. return v;
  310. }
  311. void createStringMatcher (OutputStream& out, const String& utf8PointerVariable,
  312. const StringArray& strings, const StringArray& codeToExecute, const int indentLevel)
  313. {
  314. jassert (strings.size() == codeToExecute.size());
  315. const String indent (String::repeatedString (" ", indentLevel));
  316. const int hashMultiplier = findBestHashMultiplier (strings);
  317. out << indent << "int hash = 0;" << newLine
  318. << indent << "if (" << utf8PointerVariable << " != 0)" << newLine
  319. << indent << " while (*" << utf8PointerVariable << " != 0)" << newLine
  320. << indent << " hash = " << hashMultiplier << " * hash + *" << utf8PointerVariable << "++;" << newLine
  321. << newLine
  322. << indent << "switch (hash)" << newLine
  323. << indent << "{" << newLine;
  324. for (int i = 0; i < strings.size(); ++i)
  325. {
  326. StringArray matchingStrings;
  327. matchingStrings.addTokens (strings[i], "|", "");
  328. for (int j = 0; j < matchingStrings.size(); ++j)
  329. {
  330. out << indent << " case 0x" << hexString8Digits (calculateHash (matchingStrings[j], hashMultiplier)) << ":";
  331. if (j < matchingStrings.size() - 1)
  332. out << newLine;
  333. }
  334. out << " " << codeToExecute[i] << newLine;
  335. }
  336. out << indent << " default: break;" << newLine
  337. << indent << "}" << newLine << newLine;
  338. }
  339. }