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.

488 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 boolLiteral (const bool b)
  156. {
  157. return b ? "true" : "false";
  158. }
  159. const String floatLiteral (float v)
  160. {
  161. String s ((double) v, 4);
  162. if (s.containsChar ('.'))
  163. {
  164. s = s.trimCharactersAtEnd ("0");
  165. if (s.endsWithChar ('.'))
  166. s << '0';
  167. s << 'f';
  168. }
  169. else
  170. {
  171. s << ".0f";
  172. }
  173. return s;
  174. }
  175. const String doubleLiteral (double v)
  176. {
  177. String s (v, 7);
  178. if (s.containsChar ('.'))
  179. {
  180. s = s.trimCharactersAtEnd ("0");
  181. if (s.endsWithChar ('.'))
  182. s << '0';
  183. }
  184. else
  185. {
  186. s << ".0";
  187. }
  188. return s;
  189. }
  190. const String alignFunctionCallParams (const String& call, const StringArray& parameters, const int maxLineLength)
  191. {
  192. String result, currentLine (call);
  193. for (int i = 0; i < parameters.size(); ++i)
  194. {
  195. if (currentLine.length() >= maxLineLength)
  196. {
  197. result += currentLine.trimEnd() + newLine;
  198. currentLine = String::repeatedString (" ", call.length()) + parameters[i];
  199. }
  200. else
  201. {
  202. currentLine += parameters[i];
  203. }
  204. if (i < parameters.size() - 1)
  205. currentLine << ", ";
  206. }
  207. return result + currentLine.trimEnd() + ")";
  208. }
  209. const String colourToCode (const Colour& col)
  210. {
  211. const Colour colours[] =
  212. {
  213. #define COL(col) Colours::col,
  214. #include "jucer_Colours.h"
  215. #undef COL
  216. Colours::transparentBlack
  217. };
  218. static const char* colourNames[] =
  219. {
  220. #define COL(col) #col,
  221. #include "jucer_Colours.h"
  222. #undef COL
  223. 0
  224. };
  225. for (int i = 0; i < numElementsInArray (colourNames) - 1; ++i)
  226. if (col == colours[i])
  227. return "Colours::" + String (colourNames[i]);
  228. return "Colour (0x" + hexString8Digits ((int) col.getARGB()) + ')';
  229. }
  230. const String justificationToCode (const Justification& justification)
  231. {
  232. switch (justification.getFlags())
  233. {
  234. case Justification::centred: return "Justification::centred";
  235. case Justification::centredLeft: return "Justification::centredLeft";
  236. case Justification::centredRight: return "Justification::centredRight";
  237. case Justification::centredTop: return "Justification::centredTop";
  238. case Justification::centredBottom: return "Justification::centredBottom";
  239. case Justification::topLeft: return "Justification::topLeft";
  240. case Justification::topRight: return "Justification::topRight";
  241. case Justification::bottomLeft: return "Justification::bottomLeft";
  242. case Justification::bottomRight: return "Justification::bottomRight";
  243. case Justification::left: return "Justification::left";
  244. case Justification::right: return "Justification::right";
  245. case Justification::horizontallyCentred: return "Justification::horizontallyCentred";
  246. case Justification::top: return "Justification::top";
  247. case Justification::bottom: return "Justification::bottom";
  248. case Justification::verticallyCentred: return "Justification::verticallyCentred";
  249. case Justification::horizontallyJustified: return "Justification::horizontallyJustified";
  250. default: jassertfalse; break;
  251. }
  252. return "Justification (" + String (justification.getFlags()) + ")";
  253. }
  254. const String fontToCode (const Font& font)
  255. {
  256. String s ("Font (");
  257. String name (font.getTypefaceName());
  258. if (name != Font::getDefaultSansSerifFontName())
  259. {
  260. if (name == Font::getDefaultSerifFontName())
  261. name = "Font::getDefaultSerifFontName()";
  262. else if (name == Font::getDefaultMonospacedFontName())
  263. name = "Font::getDefaultMonospacedFontName()";
  264. else
  265. name = stringLiteral (font.getTypefaceName());
  266. s << name << ", ";
  267. }
  268. s << floatLiteral (font.getHeight());
  269. if (font.isBold() && font.isItalic())
  270. s << ", Font::bold | Font::italic";
  271. else if (font.isBold())
  272. s << ", Font::bold";
  273. else if (font.isItalic())
  274. s << ", Font::italic";
  275. return s + ")";
  276. }
  277. const String castToFloat (const String& expression)
  278. {
  279. if (expression.containsOnly ("0123456789.f"))
  280. {
  281. String s (expression.getFloatValue());
  282. if (s.containsChar (T('.')))
  283. return s + "f";
  284. return s + ".0f";
  285. }
  286. return "(float) (" + expression + ")";
  287. }
  288. const String castToInt (const String& expression)
  289. {
  290. if (expression.containsOnly ("0123456789."))
  291. return String ((int) expression.getFloatValue());
  292. return "(int) (" + expression + ")";
  293. }
  294. void writeDataAsCppLiteral (const MemoryBlock& mb, OutputStream& out)
  295. {
  296. const int maxCharsOnLine = 250;
  297. const unsigned char* data = (const unsigned char*) mb.getData();
  298. int charsOnLine = 0;
  299. bool canUseStringLiteral = mb.getSize() < 32768; // MS compilers can't handle big string literals..
  300. if (canUseStringLiteral)
  301. {
  302. unsigned int numEscaped = 0;
  303. for (size_t i = 0; i < mb.getSize(); ++i)
  304. {
  305. const unsigned int num = (unsigned int) data[i];
  306. if (! ((num >= 32 && num < 127) || num == '\t' || num == '\r' || num == '\n'))
  307. {
  308. if (++numEscaped > mb.getSize() / 4)
  309. {
  310. canUseStringLiteral = false;
  311. break;
  312. }
  313. }
  314. }
  315. }
  316. if (! canUseStringLiteral)
  317. {
  318. out << "{ ";
  319. for (size_t i = 0; i < mb.getSize(); ++i)
  320. {
  321. const int num = (int) (unsigned int) data[i];
  322. out << num << ',';
  323. charsOnLine += 2;
  324. if (num >= 10)
  325. ++charsOnLine;
  326. if (num >= 100)
  327. ++charsOnLine;
  328. if (charsOnLine >= maxCharsOnLine)
  329. {
  330. charsOnLine = 0;
  331. out << newLine;
  332. }
  333. }
  334. out << "0,0 };";
  335. }
  336. else
  337. {
  338. out << "\"";
  339. writeEscapeChars (out, data, (int) mb.getSize(), maxCharsOnLine, true, false);
  340. out << "\";";
  341. }
  342. }
  343. static int calculateHash (const String& s, const int hashMultiplier)
  344. {
  345. const char* t = s.toUTF8();
  346. int hash = 0;
  347. while (*t != 0)
  348. hash = hashMultiplier * hash + *t++;
  349. return hash;
  350. }
  351. static int findBestHashMultiplier (const StringArray& strings)
  352. {
  353. int v = 31;
  354. for (;;)
  355. {
  356. SortedSet <int> hashes;
  357. bool collision = false;
  358. for (int i = strings.size(); --i >= 0;)
  359. {
  360. const int hash = calculateHash (strings[i], v);
  361. if (hashes.contains (hash))
  362. {
  363. collision = true;
  364. break;
  365. }
  366. hashes.add (hash);
  367. }
  368. if (! collision)
  369. break;
  370. v += 2;
  371. }
  372. return v;
  373. }
  374. void createStringMatcher (OutputStream& out, const String& utf8PointerVariable,
  375. const StringArray& strings, const StringArray& codeToExecute, const int indentLevel)
  376. {
  377. jassert (strings.size() == codeToExecute.size());
  378. const String indent (String::repeatedString (" ", indentLevel));
  379. const int hashMultiplier = findBestHashMultiplier (strings);
  380. out << indent << "int hash = 0;" << newLine
  381. << indent << "if (" << utf8PointerVariable << " != 0)" << newLine
  382. << indent << " while (*" << utf8PointerVariable << " != 0)" << newLine
  383. << indent << " hash = " << hashMultiplier << " * hash + *" << utf8PointerVariable << "++;" << newLine
  384. << newLine
  385. << indent << "switch (hash)" << newLine
  386. << indent << "{" << newLine;
  387. for (int i = 0; i < strings.size(); ++i)
  388. out << indent << " case 0x" << hexString8Digits (calculateHash (strings[i], hashMultiplier))
  389. << ": " << codeToExecute[i] << newLine;
  390. out << indent << " default: break;" << newLine
  391. << indent << "}" << newLine << newLine;
  392. }
  393. }