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.

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