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.

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