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.

494 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. auto space = String::repeatedString (" ", numSpaces);
  29. auto lines = StringArray::fromLines (code);
  30. for (auto& line : lines)
  31. {
  32. if (! indentFirstLine)
  33. {
  34. indentFirstLine = true;
  35. continue;
  36. }
  37. if (line.trimEnd().isNotEmpty())
  38. line = space + line;
  39. }
  40. return lines.joinIntoString (newLine);
  41. }
  42. String unindent (const String& code, const int numSpaces)
  43. {
  44. if (numSpaces == 0)
  45. return code;
  46. auto space = String::repeatedString (" ", numSpaces);
  47. auto lines = StringArray::fromLines (code);
  48. for (auto& line : lines)
  49. if (line.startsWith (space))
  50. line = line.substring (numSpaces);
  51. return lines.joinIntoString (newLine);
  52. }
  53. String makeValidIdentifier (String s, bool capitalise, bool removeColons, bool allowTemplates)
  54. {
  55. if (s.isEmpty())
  56. return "unknown";
  57. if (removeColons)
  58. s = s.replaceCharacters (".,;:/@", "______");
  59. else
  60. s = s.replaceCharacters (".,;/@", "_____");
  61. for (int i = s.length(); --i > 0;)
  62. if (CharacterFunctions::isLetter (s[i])
  63. && CharacterFunctions::isLetter (s[i - 1])
  64. && CharacterFunctions::isUpperCase (s[i])
  65. && ! CharacterFunctions::isUpperCase (s[i - 1]))
  66. s = s.substring (0, i) + " " + s.substring (i);
  67. String allowedChars ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_ 0123456789");
  68. if (allowTemplates)
  69. allowedChars += "<>";
  70. if (! removeColons)
  71. allowedChars += ":";
  72. StringArray words;
  73. words.addTokens (s.retainCharacters (allowedChars), false);
  74. words.trim();
  75. String n (words[0]);
  76. if (capitalise)
  77. n = n.toLowerCase();
  78. for (int i = 1; i < words.size(); ++i)
  79. {
  80. if (capitalise && words[i].length() > 1)
  81. n << words[i].substring (0, 1).toUpperCase()
  82. << words[i].substring (1).toLowerCase();
  83. else
  84. n << words[i];
  85. }
  86. if (CharacterFunctions::isDigit (n[0]))
  87. n = "_" + n;
  88. if (CPlusPlusCodeTokeniser::isReservedKeyword (n))
  89. n << '_';
  90. return n;
  91. }
  92. String createIncludeStatement (const File& includeFile, const File& targetFile)
  93. {
  94. return createIncludeStatement (FileHelpers::unixStylePath (FileHelpers::getRelativePathFrom (includeFile, targetFile.getParentDirectory())));
  95. }
  96. String createIncludeStatement (const String& includePath)
  97. {
  98. if (includePath.startsWithChar ('<') || includePath.startsWithChar ('"'))
  99. return "#include " + includePath;
  100. return "#include \"" + includePath + "\"";
  101. }
  102. String makeHeaderGuardName (const File& file)
  103. {
  104. return file.getFileName().toUpperCase()
  105. .replaceCharacters (" .", "__")
  106. .retainCharacters ("_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
  107. + "_INCLUDED";
  108. }
  109. String makeBinaryDataIdentifierName (const File& file)
  110. {
  111. return makeValidIdentifier (file.getFileName()
  112. .replaceCharacters (" .", "__")
  113. .retainCharacters ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_0123456789"),
  114. false, true, false);
  115. }
  116. String stringLiteral (const String& text, int maxLineLength)
  117. {
  118. if (text.isEmpty())
  119. return "String()";
  120. StringArray lines;
  121. {
  122. String::CharPointerType t (text.getCharPointer());
  123. bool finished = t.isEmpty();
  124. while (! finished)
  125. {
  126. for (String::CharPointerType startOfLine (t);;)
  127. {
  128. switch (t.getAndAdvance())
  129. {
  130. case 0: finished = true; break;
  131. case '\n': break;
  132. case '\r': if (*t == '\n') ++t; break;
  133. default: continue;
  134. }
  135. lines.add (String (startOfLine, t));
  136. break;
  137. }
  138. }
  139. }
  140. if (maxLineLength > 0)
  141. {
  142. for (int i = 0; i < lines.size(); ++i)
  143. {
  144. String& line = lines.getReference (i);
  145. if (line.length() > maxLineLength)
  146. {
  147. const String start (line.substring (0, maxLineLength));
  148. const String end (line.substring (maxLineLength));
  149. line = start;
  150. lines.insert (i + 1, end);
  151. }
  152. }
  153. }
  154. for (int i = 0; i < lines.size(); ++i)
  155. lines.getReference(i) = CppTokeniserFunctions::addEscapeChars (lines.getReference(i));
  156. lines.removeEmptyStrings();
  157. for (int i = 0; i < lines.size(); ++i)
  158. lines.getReference(i) = "\"" + lines.getReference(i) + "\"";
  159. String result (lines.joinIntoString (newLine));
  160. if (! CharPointer_ASCII::isValidString (text.toUTF8(), std::numeric_limits<int>::max()))
  161. result = "CharPointer_UTF8 (" + result + ")";
  162. return result;
  163. }
  164. String alignFunctionCallParams (const String& call, const StringArray& parameters, const int maxLineLength)
  165. {
  166. String result, currentLine (call);
  167. for (int i = 0; i < parameters.size(); ++i)
  168. {
  169. if (currentLine.length() >= maxLineLength)
  170. {
  171. result += currentLine.trimEnd() + newLine;
  172. currentLine = String::repeatedString (" ", call.length()) + parameters[i];
  173. }
  174. else
  175. {
  176. currentLine += parameters[i];
  177. }
  178. if (i < parameters.size() - 1)
  179. currentLine << ", ";
  180. }
  181. return result + currentLine.trimEnd() + ")";
  182. }
  183. String floatLiteral (double value, int numDecPlaces)
  184. {
  185. String s (value, numDecPlaces);
  186. if (s.containsChar ('.'))
  187. s << 'f';
  188. else
  189. s << ".0f";
  190. return s;
  191. }
  192. String boolLiteral (bool value)
  193. {
  194. return value ? "true" : "false";
  195. }
  196. String colourToCode (Colour col)
  197. {
  198. const Colour colours[] =
  199. {
  200. #define COL(col) Colours::col,
  201. #include "jucer_Colours.h"
  202. #undef COL
  203. Colours::transparentBlack
  204. };
  205. static const char* colourNames[] =
  206. {
  207. #define COL(col) #col,
  208. #include "jucer_Colours.h"
  209. #undef COL
  210. 0
  211. };
  212. for (int i = 0; i < numElementsInArray (colourNames) - 1; ++i)
  213. if (col == colours[i])
  214. return "Colours::" + String (colourNames[i]);
  215. return "Colour (0x" + hexString8Digits ((int) col.getARGB()) + ')';
  216. }
  217. String justificationToCode (Justification justification)
  218. {
  219. switch (justification.getFlags())
  220. {
  221. case Justification::centred: return "Justification::centred";
  222. case Justification::centredLeft: return "Justification::centredLeft";
  223. case Justification::centredRight: return "Justification::centredRight";
  224. case Justification::centredTop: return "Justification::centredTop";
  225. case Justification::centredBottom: return "Justification::centredBottom";
  226. case Justification::topLeft: return "Justification::topLeft";
  227. case Justification::topRight: return "Justification::topRight";
  228. case Justification::bottomLeft: return "Justification::bottomLeft";
  229. case Justification::bottomRight: return "Justification::bottomRight";
  230. case Justification::left: return "Justification::left";
  231. case Justification::right: return "Justification::right";
  232. case Justification::horizontallyCentred: return "Justification::horizontallyCentred";
  233. case Justification::top: return "Justification::top";
  234. case Justification::bottom: return "Justification::bottom";
  235. case Justification::verticallyCentred: return "Justification::verticallyCentred";
  236. case Justification::horizontallyJustified: return "Justification::horizontallyJustified";
  237. default: break;
  238. }
  239. jassertfalse;
  240. return "Justification (" + String (justification.getFlags()) + ")";
  241. }
  242. void writeDataAsCppLiteral (const MemoryBlock& mb, OutputStream& out,
  243. bool breakAtNewLines, bool allowStringBreaks)
  244. {
  245. const int maxCharsOnLine = 250;
  246. const unsigned char* data = (const unsigned char*) mb.getData();
  247. int charsOnLine = 0;
  248. bool canUseStringLiteral = mb.getSize() < 32768; // MS compilers can't handle big string literals..
  249. if (canUseStringLiteral)
  250. {
  251. unsigned int numEscaped = 0;
  252. for (size_t i = 0; i < mb.getSize(); ++i)
  253. {
  254. const unsigned int num = (unsigned int) data[i];
  255. if (! ((num >= 32 && num < 127) || num == '\t' || num == '\r' || num == '\n'))
  256. {
  257. if (++numEscaped > mb.getSize() / 4)
  258. {
  259. canUseStringLiteral = false;
  260. break;
  261. }
  262. }
  263. }
  264. }
  265. if (! canUseStringLiteral)
  266. {
  267. out << "{ ";
  268. for (size_t i = 0; i < mb.getSize(); ++i)
  269. {
  270. const int num = (int) (unsigned int) data[i];
  271. out << num << ',';
  272. charsOnLine += 2;
  273. if (num >= 10)
  274. {
  275. ++charsOnLine;
  276. if (num >= 100)
  277. ++charsOnLine;
  278. }
  279. if (charsOnLine >= maxCharsOnLine)
  280. {
  281. charsOnLine = 0;
  282. out << newLine;
  283. }
  284. }
  285. out << "0,0 };";
  286. }
  287. else
  288. {
  289. out << "\"";
  290. CppTokeniserFunctions::writeEscapeChars (out, (const char*) data, (int) mb.getSize(),
  291. maxCharsOnLine, breakAtNewLines, false, allowStringBreaks);
  292. out << "\";";
  293. }
  294. }
  295. //==============================================================================
  296. static unsigned int calculateHash (const String& s, const unsigned int hashMultiplier)
  297. {
  298. const char* t = s.toUTF8();
  299. unsigned int hash = 0;
  300. while (*t != 0)
  301. hash = hashMultiplier * hash + (unsigned int) *t++;
  302. return hash;
  303. }
  304. static unsigned int findBestHashMultiplier (const StringArray& strings)
  305. {
  306. unsigned int v = 31;
  307. for (;;)
  308. {
  309. SortedSet <unsigned int> hashes;
  310. bool collision = false;
  311. for (int i = strings.size(); --i >= 0;)
  312. {
  313. const unsigned int hash = calculateHash (strings[i], v);
  314. if (hashes.contains (hash))
  315. {
  316. collision = true;
  317. break;
  318. }
  319. hashes.add (hash);
  320. }
  321. if (! collision)
  322. break;
  323. v += 2;
  324. }
  325. return v;
  326. }
  327. void createStringMatcher (OutputStream& out, const String& utf8PointerVariable,
  328. const StringArray& strings, const StringArray& codeToExecute, const int indentLevel)
  329. {
  330. jassert (strings.size() == codeToExecute.size());
  331. const String indent (String::repeatedString (" ", indentLevel));
  332. const unsigned int hashMultiplier = findBestHashMultiplier (strings);
  333. out << indent << "unsigned int hash = 0;" << newLine
  334. << indent << "if (" << utf8PointerVariable << " != 0)" << newLine
  335. << indent << " while (*" << utf8PointerVariable << " != 0)" << newLine
  336. << indent << " hash = " << (int) hashMultiplier << " * hash + (unsigned int) *" << utf8PointerVariable << "++;" << newLine
  337. << newLine
  338. << indent << "switch (hash)" << newLine
  339. << indent << "{" << newLine;
  340. for (int i = 0; i < strings.size(); ++i)
  341. {
  342. out << indent << " case 0x" << hexString8Digits ((int) calculateHash (strings[i], hashMultiplier))
  343. << ": " << codeToExecute[i] << newLine;
  344. }
  345. out << indent << " default: break;" << newLine
  346. << indent << "}" << newLine << newLine;
  347. }
  348. String getLeadingWhitespace (String line)
  349. {
  350. line = line.removeCharacters ("\r\n");
  351. const String::CharPointerType endOfLeadingWS (line.getCharPointer().findEndOfWhitespace());
  352. return String (line.getCharPointer(), endOfLeadingWS);
  353. }
  354. int getBraceCount (String::CharPointerType line)
  355. {
  356. int braces = 0;
  357. for (;;)
  358. {
  359. const juce_wchar c = line.getAndAdvance();
  360. if (c == 0) break;
  361. else if (c == '{') ++braces;
  362. else if (c == '}') --braces;
  363. else if (c == '/') { if (*line == '/') break; }
  364. else if (c == '"' || c == '\'') { while (! (line.isEmpty() || line.getAndAdvance() == c)) {} }
  365. }
  366. return braces;
  367. }
  368. bool getIndentForCurrentBlock (CodeDocument::Position pos, const String& tab,
  369. String& blockIndent, String& lastLineIndent)
  370. {
  371. int braceCount = 0;
  372. bool indentFound = false;
  373. while (pos.getLineNumber() > 0)
  374. {
  375. pos = pos.movedByLines (-1);
  376. const String line (pos.getLineText());
  377. const String trimmedLine (line.trimStart());
  378. braceCount += getBraceCount (trimmedLine.getCharPointer());
  379. if (braceCount > 0)
  380. {
  381. blockIndent = getLeadingWhitespace (line);
  382. if (! indentFound)
  383. lastLineIndent = blockIndent + tab;
  384. return true;
  385. }
  386. if ((! indentFound) && trimmedLine.isNotEmpty())
  387. {
  388. indentFound = true;
  389. lastLineIndent = getLeadingWhitespace (line);
  390. }
  391. }
  392. return false;
  393. }
  394. }