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.

513 lines
17KB

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