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.

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