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.

505 lines
17KB

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