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.

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