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.

457 lines
15KB

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