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.

484 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. return "#include \"" + includePath + "\"";
  157. }
  158. String makeHeaderGuardName (const File& file)
  159. {
  160. return "__" + file.getFileName().toUpperCase()
  161. .replaceCharacters (" .", "__")
  162. .retainCharacters ("_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
  163. + "_" + String::toHexString (file.hashCode()).toUpperCase() + "__";
  164. }
  165. String makeBinaryDataIdentifierName (const File& file)
  166. {
  167. return makeValidIdentifier (file.getFileName()
  168. .replaceCharacters (" .", "__")
  169. .retainCharacters ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_0123456789"),
  170. false, true, false);
  171. }
  172. String stringLiteral (const String& text, int maxLineLength)
  173. {
  174. if (text.isEmpty())
  175. return "String::empty";
  176. StringArray lines;
  177. lines.add (text);
  178. if (maxLineLength > 0)
  179. {
  180. while (lines [lines.size() - 1].length() > maxLineLength)
  181. {
  182. String& lastLine = lines.getReference (lines.size() - 1);
  183. const String start (lastLine.substring (0, maxLineLength));
  184. const String end (lastLine.substring (maxLineLength));
  185. lastLine = start;
  186. lines.add (end);
  187. }
  188. }
  189. for (int i = 0; i < lines.size(); ++i)
  190. lines.getReference(i) = "\"" + addEscapeChars (lines.getReference(i)) + "\"";
  191. String result (lines.joinIntoString (newLine));
  192. if (! CharPointer_ASCII::isValidString (text.toUTF8(), std::numeric_limits<int>::max()))
  193. result = "CharPointer_UTF8 (" + result + ")";
  194. return result;
  195. }
  196. String alignFunctionCallParams (const String& call, const StringArray& parameters, const int maxLineLength)
  197. {
  198. String result, currentLine (call);
  199. for (int i = 0; i < parameters.size(); ++i)
  200. {
  201. if (currentLine.length() >= maxLineLength)
  202. {
  203. result += currentLine.trimEnd() + newLine;
  204. currentLine = String::repeatedString (" ", call.length()) + parameters[i];
  205. }
  206. else
  207. {
  208. currentLine += parameters[i];
  209. }
  210. if (i < parameters.size() - 1)
  211. currentLine << ", ";
  212. }
  213. return result + currentLine.trimEnd() + ")";
  214. }
  215. String colourToCode (const Colour& col)
  216. {
  217. const Colour colours[] =
  218. {
  219. #define COL(col) Colours::col,
  220. #include "jucer_Colours.h"
  221. #undef COL
  222. Colours::transparentBlack
  223. };
  224. static const char* colourNames[] =
  225. {
  226. #define COL(col) #col,
  227. #include "jucer_Colours.h"
  228. #undef COL
  229. 0
  230. };
  231. for (int i = 0; i < numElementsInArray (colourNames) - 1; ++i)
  232. if (col == colours[i])
  233. return "Colours::" + String (colourNames[i]);
  234. return "Colour (0x" + hexString8Digits ((int) col.getARGB()) + ')';
  235. }
  236. void writeDataAsCppLiteral (const MemoryBlock& mb, OutputStream& out,
  237. bool breakAtNewLines, bool allowStringBreaks)
  238. {
  239. const int maxCharsOnLine = 250;
  240. const unsigned char* data = (const unsigned char*) mb.getData();
  241. int charsOnLine = 0;
  242. bool canUseStringLiteral = mb.getSize() < 32768; // MS compilers can't handle big string literals..
  243. if (canUseStringLiteral)
  244. {
  245. unsigned int numEscaped = 0;
  246. for (size_t i = 0; i < mb.getSize(); ++i)
  247. {
  248. const unsigned int num = (unsigned int) data[i];
  249. if (! ((num >= 32 && num < 127) || num == '\t' || num == '\r' || num == '\n'))
  250. {
  251. if (++numEscaped > mb.getSize() / 4)
  252. {
  253. canUseStringLiteral = false;
  254. break;
  255. }
  256. }
  257. }
  258. }
  259. if (! canUseStringLiteral)
  260. {
  261. out << "{ ";
  262. for (size_t i = 0; i < mb.getSize(); ++i)
  263. {
  264. const int num = (int) (unsigned int) data[i];
  265. out << num << ',';
  266. charsOnLine += 2;
  267. if (num >= 10)
  268. {
  269. ++charsOnLine;
  270. if (num >= 100)
  271. ++charsOnLine;
  272. }
  273. if (charsOnLine >= maxCharsOnLine)
  274. {
  275. charsOnLine = 0;
  276. out << newLine;
  277. }
  278. }
  279. out << "0,0 };";
  280. }
  281. else
  282. {
  283. out << "\"";
  284. writeEscapeChars (out, (const char*) data, (int) mb.getSize(),
  285. maxCharsOnLine, breakAtNewLines, false, allowStringBreaks);
  286. out << "\";";
  287. }
  288. }
  289. //==============================================================================
  290. static unsigned int calculateHash (const String& s, const int hashMultiplier)
  291. {
  292. const char* t = s.toUTF8();
  293. unsigned int hash = 0;
  294. while (*t != 0)
  295. hash = hashMultiplier * hash + (unsigned int) *t++;
  296. return hash;
  297. }
  298. static int findBestHashMultiplier (const StringArray& strings)
  299. {
  300. int v = 31;
  301. for (;;)
  302. {
  303. SortedSet <unsigned int> hashes;
  304. bool collision = false;
  305. for (int i = strings.size(); --i >= 0;)
  306. {
  307. const unsigned int hash = calculateHash (strings[i], v);
  308. if (hashes.contains (hash))
  309. {
  310. collision = true;
  311. break;
  312. }
  313. hashes.add (hash);
  314. }
  315. if (! collision)
  316. break;
  317. v += 2;
  318. }
  319. return v;
  320. }
  321. void createStringMatcher (OutputStream& out, const String& utf8PointerVariable,
  322. const StringArray& strings, const StringArray& codeToExecute, const int indentLevel)
  323. {
  324. jassert (strings.size() == codeToExecute.size());
  325. const String indent (String::repeatedString (" ", indentLevel));
  326. const int hashMultiplier = findBestHashMultiplier (strings);
  327. out << indent << "unsigned int hash = 0;" << newLine
  328. << indent << "if (" << utf8PointerVariable << " != 0)" << newLine
  329. << indent << " while (*" << utf8PointerVariable << " != 0)" << newLine
  330. << indent << " hash = " << hashMultiplier << " * hash + (unsigned int) *" << utf8PointerVariable << "++;" << newLine
  331. << newLine
  332. << indent << "switch (hash)" << newLine
  333. << indent << "{" << newLine;
  334. for (int i = 0; i < strings.size(); ++i)
  335. {
  336. out << indent << " case 0x" << hexString8Digits (calculateHash (strings[i], hashMultiplier))
  337. << ": " << codeToExecute[i] << newLine;
  338. }
  339. out << indent << " default: break;" << newLine
  340. << indent << "}" << newLine << newLine;
  341. }
  342. String getLeadingWhitespace (String line)
  343. {
  344. line = line.removeCharacters ("\r\n");
  345. const String::CharPointerType endOfLeadingWS (line.getCharPointer().findEndOfWhitespace());
  346. return String (line.getCharPointer(), endOfLeadingWS);
  347. }
  348. int getBraceCount (String::CharPointerType line)
  349. {
  350. int braces = 0;
  351. for (;;)
  352. {
  353. const juce_wchar c = line.getAndAdvance();
  354. if (c == 0) break;
  355. else if (c == '{') ++braces;
  356. else if (c == '}') --braces;
  357. else if (c == '/') { if (*line == '/') break; }
  358. else if (c == '"' || c == '\'') { while (! (line.isEmpty() || line.getAndAdvance() == c)) {} }
  359. }
  360. return braces;
  361. }
  362. bool getIndentForCurrentBlock (CodeDocument::Position pos, const String& tab,
  363. String& blockIndent, String& lastLineIndent)
  364. {
  365. int braceCount = 0;
  366. bool indentFound = false;
  367. while (pos.getLineNumber() > 0)
  368. {
  369. pos = pos.movedByLines (-1);
  370. const String line (pos.getLineText());
  371. const String trimmedLine (line.trimStart());
  372. braceCount += getBraceCount (trimmedLine.getCharPointer());
  373. if (braceCount > 0)
  374. {
  375. blockIndent = getLeadingWhitespace (line);
  376. if (! indentFound)
  377. lastLineIndent = blockIndent + tab;
  378. return true;
  379. }
  380. if ((! indentFound) && trimmedLine.isNotEmpty())
  381. {
  382. indentFound = true;
  383. lastLineIndent = getLeadingWhitespace (line);
  384. }
  385. }
  386. return false;
  387. }
  388. }