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.

478 lines
16KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 5 End-User License
  8. Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
  9. 27th April 2017).
  10. End User License Agreement: www.juce.com/juce-5-licence
  11. Privacy Policy: www.juce.com/juce-5-privacy-policy
  12. Or: You may also use this code under the terms of the GPL v3 (see
  13. www.gnu.org/licenses).
  14. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  15. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  16. DISCLAIMED.
  17. ==============================================================================
  18. */
  19. #include "../jucer_Headers.h"
  20. #include "jucer_CodeHelpers.h"
  21. //==============================================================================
  22. namespace CodeHelpers
  23. {
  24. String indent (const String& code, const int numSpaces, bool indentFirstLine)
  25. {
  26. if (numSpaces == 0)
  27. return code;
  28. const String space (String::repeatedString (" ", numSpaces));
  29. StringArray lines;
  30. lines.addLines (code);
  31. for (int i = (indentFirstLine ? 0 : 1); i < lines.size(); ++i)
  32. {
  33. String s (lines[i].trimEnd());
  34. if (s.isNotEmpty())
  35. s = space + s;
  36. lines.set (i, s);
  37. }
  38. return lines.joinIntoString (newLine);
  39. }
  40. String makeValidIdentifier (String s, bool capitalise, bool removeColons, bool allowTemplates)
  41. {
  42. if (s.isEmpty())
  43. return "unknown";
  44. if (removeColons)
  45. s = s.replaceCharacters (".,;:/@", "______");
  46. else
  47. s = s.replaceCharacters (".,;/@", "_____");
  48. for (int 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 (int 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. String createIncludeStatement (const File& includeFile, const File& targetFile)
  80. {
  81. return createIncludeStatement (FileHelpers::unixStylePath (FileHelpers::getRelativePathFrom (includeFile, targetFile.getParentDirectory())));
  82. }
  83. String createIncludeStatement (const String& includePath)
  84. {
  85. if (includePath.startsWithChar ('<') || includePath.startsWithChar ('"'))
  86. return "#include " + includePath;
  87. return "#include \"" + includePath + "\"";
  88. }
  89. String makeHeaderGuardName (const File& file)
  90. {
  91. return file.getFileName().toUpperCase()
  92. .replaceCharacters (" .", "__")
  93. .retainCharacters ("_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
  94. + "_INCLUDED";
  95. }
  96. String makeBinaryDataIdentifierName (const File& file)
  97. {
  98. return makeValidIdentifier (file.getFileName()
  99. .replaceCharacters (" .", "__")
  100. .retainCharacters ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_0123456789"),
  101. false, true, false);
  102. }
  103. String stringLiteral (const String& text, int maxLineLength)
  104. {
  105. if (text.isEmpty())
  106. return "String()";
  107. StringArray lines;
  108. {
  109. String::CharPointerType t (text.getCharPointer());
  110. bool finished = t.isEmpty();
  111. while (! finished)
  112. {
  113. for (String::CharPointerType startOfLine (t);;)
  114. {
  115. switch (t.getAndAdvance())
  116. {
  117. case 0: finished = true; break;
  118. case '\n': break;
  119. case '\r': if (*t == '\n') ++t; break;
  120. default: continue;
  121. }
  122. lines.add (String (startOfLine, t));
  123. break;
  124. }
  125. }
  126. }
  127. if (maxLineLength > 0)
  128. {
  129. for (int i = 0; i < lines.size(); ++i)
  130. {
  131. String& line = lines.getReference (i);
  132. if (line.length() > maxLineLength)
  133. {
  134. const String start (line.substring (0, maxLineLength));
  135. const String end (line.substring (maxLineLength));
  136. line = start;
  137. lines.insert (i + 1, end);
  138. }
  139. }
  140. }
  141. for (int i = 0; i < lines.size(); ++i)
  142. lines.getReference(i) = CppTokeniserFunctions::addEscapeChars (lines.getReference(i));
  143. lines.removeEmptyStrings();
  144. for (int i = 0; i < lines.size(); ++i)
  145. lines.getReference(i) = "\"" + lines.getReference(i) + "\"";
  146. String result (lines.joinIntoString (newLine));
  147. if (! CharPointer_ASCII::isValidString (text.toUTF8(), std::numeric_limits<int>::max()))
  148. result = "CharPointer_UTF8 (" + result + ")";
  149. return result;
  150. }
  151. String alignFunctionCallParams (const String& call, const StringArray& parameters, const int maxLineLength)
  152. {
  153. String result, currentLine (call);
  154. for (int i = 0; i < parameters.size(); ++i)
  155. {
  156. if (currentLine.length() >= maxLineLength)
  157. {
  158. result += currentLine.trimEnd() + newLine;
  159. currentLine = String::repeatedString (" ", call.length()) + parameters[i];
  160. }
  161. else
  162. {
  163. currentLine += parameters[i];
  164. }
  165. if (i < parameters.size() - 1)
  166. currentLine << ", ";
  167. }
  168. return result + currentLine.trimEnd() + ")";
  169. }
  170. String floatLiteral (double value, int numDecPlaces)
  171. {
  172. String s (value, numDecPlaces);
  173. if (s.containsChar ('.'))
  174. s << 'f';
  175. else
  176. s << ".0f";
  177. return s;
  178. }
  179. String boolLiteral (bool value)
  180. {
  181. return value ? "true" : "false";
  182. }
  183. String colourToCode (Colour col)
  184. {
  185. const Colour colours[] =
  186. {
  187. #define COL(col) Colours::col,
  188. #include "jucer_Colours.h"
  189. #undef COL
  190. Colours::transparentBlack
  191. };
  192. static const char* colourNames[] =
  193. {
  194. #define COL(col) #col,
  195. #include "jucer_Colours.h"
  196. #undef COL
  197. 0
  198. };
  199. for (int i = 0; i < numElementsInArray (colourNames) - 1; ++i)
  200. if (col == colours[i])
  201. return "Colours::" + String (colourNames[i]);
  202. return "Colour (0x" + hexString8Digits ((int) col.getARGB()) + ')';
  203. }
  204. String justificationToCode (Justification justification)
  205. {
  206. switch (justification.getFlags())
  207. {
  208. case Justification::centred: return "Justification::centred";
  209. case Justification::centredLeft: return "Justification::centredLeft";
  210. case Justification::centredRight: return "Justification::centredRight";
  211. case Justification::centredTop: return "Justification::centredTop";
  212. case Justification::centredBottom: return "Justification::centredBottom";
  213. case Justification::topLeft: return "Justification::topLeft";
  214. case Justification::topRight: return "Justification::topRight";
  215. case Justification::bottomLeft: return "Justification::bottomLeft";
  216. case Justification::bottomRight: return "Justification::bottomRight";
  217. case Justification::left: return "Justification::left";
  218. case Justification::right: return "Justification::right";
  219. case Justification::horizontallyCentred: return "Justification::horizontallyCentred";
  220. case Justification::top: return "Justification::top";
  221. case Justification::bottom: return "Justification::bottom";
  222. case Justification::verticallyCentred: return "Justification::verticallyCentred";
  223. case Justification::horizontallyJustified: return "Justification::horizontallyJustified";
  224. default: break;
  225. }
  226. jassertfalse;
  227. return "Justification (" + String (justification.getFlags()) + ")";
  228. }
  229. void writeDataAsCppLiteral (const MemoryBlock& mb, OutputStream& out,
  230. bool breakAtNewLines, bool allowStringBreaks)
  231. {
  232. const int maxCharsOnLine = 250;
  233. const unsigned char* data = (const unsigned char*) mb.getData();
  234. int charsOnLine = 0;
  235. bool canUseStringLiteral = mb.getSize() < 32768; // MS compilers can't handle big string literals..
  236. if (canUseStringLiteral)
  237. {
  238. unsigned int numEscaped = 0;
  239. for (size_t i = 0; i < mb.getSize(); ++i)
  240. {
  241. const unsigned int num = (unsigned int) data[i];
  242. if (! ((num >= 32 && num < 127) || num == '\t' || num == '\r' || num == '\n'))
  243. {
  244. if (++numEscaped > mb.getSize() / 4)
  245. {
  246. canUseStringLiteral = false;
  247. break;
  248. }
  249. }
  250. }
  251. }
  252. if (! canUseStringLiteral)
  253. {
  254. out << "{ ";
  255. for (size_t i = 0; i < mb.getSize(); ++i)
  256. {
  257. const int num = (int) (unsigned int) data[i];
  258. out << num << ',';
  259. charsOnLine += 2;
  260. if (num >= 10)
  261. {
  262. ++charsOnLine;
  263. if (num >= 100)
  264. ++charsOnLine;
  265. }
  266. if (charsOnLine >= maxCharsOnLine)
  267. {
  268. charsOnLine = 0;
  269. out << newLine;
  270. }
  271. }
  272. out << "0,0 };";
  273. }
  274. else
  275. {
  276. out << "\"";
  277. CppTokeniserFunctions::writeEscapeChars (out, (const char*) data, (int) mb.getSize(),
  278. maxCharsOnLine, breakAtNewLines, false, allowStringBreaks);
  279. out << "\";";
  280. }
  281. }
  282. //==============================================================================
  283. static unsigned int calculateHash (const String& s, const unsigned int hashMultiplier)
  284. {
  285. const char* t = s.toUTF8();
  286. unsigned int hash = 0;
  287. while (*t != 0)
  288. hash = hashMultiplier * hash + (unsigned int) *t++;
  289. return hash;
  290. }
  291. static unsigned int findBestHashMultiplier (const StringArray& strings)
  292. {
  293. unsigned int v = 31;
  294. for (;;)
  295. {
  296. SortedSet <unsigned int> hashes;
  297. bool collision = false;
  298. for (int i = strings.size(); --i >= 0;)
  299. {
  300. const unsigned int hash = calculateHash (strings[i], v);
  301. if (hashes.contains (hash))
  302. {
  303. collision = true;
  304. break;
  305. }
  306. hashes.add (hash);
  307. }
  308. if (! collision)
  309. break;
  310. v += 2;
  311. }
  312. return v;
  313. }
  314. void createStringMatcher (OutputStream& out, const String& utf8PointerVariable,
  315. const StringArray& strings, const StringArray& codeToExecute, const int indentLevel)
  316. {
  317. jassert (strings.size() == codeToExecute.size());
  318. const String indent (String::repeatedString (" ", indentLevel));
  319. const unsigned int hashMultiplier = findBestHashMultiplier (strings);
  320. out << indent << "unsigned int hash = 0;" << newLine
  321. << indent << "if (" << utf8PointerVariable << " != 0)" << newLine
  322. << indent << " while (*" << utf8PointerVariable << " != 0)" << newLine
  323. << indent << " hash = " << (int) hashMultiplier << " * hash + (unsigned int) *" << utf8PointerVariable << "++;" << newLine
  324. << newLine
  325. << indent << "switch (hash)" << newLine
  326. << indent << "{" << newLine;
  327. for (int i = 0; i < strings.size(); ++i)
  328. {
  329. out << indent << " case 0x" << hexString8Digits ((int) calculateHash (strings[i], hashMultiplier))
  330. << ": " << codeToExecute[i] << newLine;
  331. }
  332. out << indent << " default: break;" << newLine
  333. << indent << "}" << newLine << newLine;
  334. }
  335. String getLeadingWhitespace (String line)
  336. {
  337. line = line.removeCharacters ("\r\n");
  338. const String::CharPointerType endOfLeadingWS (line.getCharPointer().findEndOfWhitespace());
  339. return String (line.getCharPointer(), endOfLeadingWS);
  340. }
  341. int getBraceCount (String::CharPointerType line)
  342. {
  343. int braces = 0;
  344. for (;;)
  345. {
  346. const juce_wchar c = line.getAndAdvance();
  347. if (c == 0) break;
  348. else if (c == '{') ++braces;
  349. else if (c == '}') --braces;
  350. else if (c == '/') { if (*line == '/') break; }
  351. else if (c == '"' || c == '\'') { while (! (line.isEmpty() || line.getAndAdvance() == c)) {} }
  352. }
  353. return braces;
  354. }
  355. bool getIndentForCurrentBlock (CodeDocument::Position pos, const String& tab,
  356. String& blockIndent, String& lastLineIndent)
  357. {
  358. int braceCount = 0;
  359. bool indentFound = false;
  360. while (pos.getLineNumber() > 0)
  361. {
  362. pos = pos.movedByLines (-1);
  363. const String line (pos.getLineText());
  364. const String trimmedLine (line.trimStart());
  365. braceCount += getBraceCount (trimmedLine.getCharPointer());
  366. if (braceCount > 0)
  367. {
  368. blockIndent = getLeadingWhitespace (line);
  369. if (! indentFound)
  370. lastLineIndent = blockIndent + tab;
  371. return true;
  372. }
  373. if ((! indentFound) && trimmedLine.isNotEmpty())
  374. {
  375. indentFound = true;
  376. lastLineIndent = getLeadingWhitespace (line);
  377. }
  378. }
  379. return false;
  380. }
  381. }