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.

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