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.

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