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.

493 lines
16KB

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