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.

876 lines
25KB

  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. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. XmlDocument::XmlDocument (const String& text) : originalText (text) {}
  20. XmlDocument::XmlDocument (const File& file) : inputSource (new FileInputSource (file)) {}
  21. XmlDocument::~XmlDocument() {}
  22. XmlElement* XmlDocument::parse (const File& file)
  23. {
  24. XmlDocument doc (file);
  25. return doc.getDocumentElement();
  26. }
  27. XmlElement* XmlDocument::parse (const String& xmlData)
  28. {
  29. XmlDocument doc (xmlData);
  30. return doc.getDocumentElement();
  31. }
  32. std::unique_ptr<XmlElement> parseXML (const String& textToParse)
  33. {
  34. return std::unique_ptr<XmlElement> (XmlDocument::parse (textToParse));
  35. }
  36. std::unique_ptr<XmlElement> parseXML (const File& fileToParse)
  37. {
  38. return std::unique_ptr<XmlElement> (XmlDocument::parse (fileToParse));
  39. }
  40. void XmlDocument::setInputSource (InputSource* newSource) noexcept
  41. {
  42. inputSource.reset (newSource);
  43. }
  44. void XmlDocument::setEmptyTextElementsIgnored (bool shouldBeIgnored) noexcept
  45. {
  46. ignoreEmptyTextElements = shouldBeIgnored;
  47. }
  48. namespace XmlIdentifierChars
  49. {
  50. static bool isIdentifierCharSlow (juce_wchar c) noexcept
  51. {
  52. return CharacterFunctions::isLetterOrDigit (c)
  53. || c == '_' || c == '-' || c == ':' || c == '.';
  54. }
  55. static bool isIdentifierChar (juce_wchar c) noexcept
  56. {
  57. static const uint32 legalChars[] = { 0, 0x7ff6000, 0x87fffffe, 0x7fffffe, 0 };
  58. return ((int) c < (int) numElementsInArray (legalChars) * 32) ? ((legalChars [c >> 5] & (1 << (c & 31))) != 0)
  59. : isIdentifierCharSlow (c);
  60. }
  61. /*static void generateIdentifierCharConstants()
  62. {
  63. uint32 n[8] = { 0 };
  64. for (int i = 0; i < 256; ++i)
  65. if (isIdentifierCharSlow (i))
  66. n[i >> 5] |= (1 << (i & 31));
  67. String s;
  68. for (int i = 0; i < 8; ++i)
  69. s << "0x" << String::toHexString ((int) n[i]) << ", ";
  70. DBG (s);
  71. }*/
  72. static String::CharPointerType findEndOfToken (String::CharPointerType p) noexcept
  73. {
  74. while (isIdentifierChar (*p))
  75. ++p;
  76. return p;
  77. }
  78. }
  79. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  80. {
  81. if (originalText.isEmpty() && inputSource != nullptr)
  82. {
  83. std::unique_ptr<InputStream> in (inputSource->createInputStream());
  84. if (in != nullptr)
  85. {
  86. MemoryOutputStream data;
  87. data.writeFromInputStream (*in, onlyReadOuterDocumentElement ? 8192 : -1);
  88. #if JUCE_STRING_UTF_TYPE == 8
  89. if (data.getDataSize() > 2)
  90. {
  91. data.writeByte (0);
  92. auto* text = static_cast<const char*> (data.getData());
  93. if (CharPointer_UTF16::isByteOrderMarkBigEndian (text)
  94. || CharPointer_UTF16::isByteOrderMarkLittleEndian (text))
  95. {
  96. originalText = data.toString();
  97. }
  98. else
  99. {
  100. if (CharPointer_UTF8::isByteOrderMark (text))
  101. text += 3;
  102. // parse the input buffer directly to avoid copying it all to a string..
  103. return parseDocumentElement (String::CharPointerType (text), onlyReadOuterDocumentElement);
  104. }
  105. }
  106. #else
  107. originalText = data.toString();
  108. #endif
  109. }
  110. }
  111. return parseDocumentElement (originalText.getCharPointer(), onlyReadOuterDocumentElement);
  112. }
  113. const String& XmlDocument::getLastParseError() const noexcept
  114. {
  115. return lastError;
  116. }
  117. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  118. {
  119. lastError = desc;
  120. errorOccurred = ! carryOn;
  121. }
  122. String XmlDocument::getFileContents (const String& filename) const
  123. {
  124. if (inputSource != nullptr)
  125. {
  126. std::unique_ptr<InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  127. if (in != nullptr)
  128. return in->readEntireStreamAsString();
  129. }
  130. return {};
  131. }
  132. juce_wchar XmlDocument::readNextChar() noexcept
  133. {
  134. auto c = input.getAndAdvance();
  135. if (c == 0)
  136. {
  137. outOfData = true;
  138. --input;
  139. }
  140. return c;
  141. }
  142. XmlElement* XmlDocument::parseDocumentElement (String::CharPointerType textToParse,
  143. const bool onlyReadOuterDocumentElement)
  144. {
  145. input = textToParse;
  146. errorOccurred = false;
  147. outOfData = false;
  148. needToLoadDTD = true;
  149. if (textToParse.isEmpty())
  150. {
  151. lastError = "not enough input";
  152. }
  153. else if (! parseHeader())
  154. {
  155. lastError = "malformed header";
  156. }
  157. else if (! parseDTD())
  158. {
  159. lastError = "malformed DTD";
  160. }
  161. else
  162. {
  163. lastError.clear();
  164. std::unique_ptr<XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  165. if (! errorOccurred)
  166. return result.release();
  167. }
  168. return nullptr;
  169. }
  170. bool XmlDocument::parseHeader()
  171. {
  172. skipNextWhiteSpace();
  173. if (CharacterFunctions::compareUpTo (input, CharPointer_ASCII ("<?xml"), 5) == 0)
  174. {
  175. auto headerEnd = CharacterFunctions::find (input, CharPointer_ASCII ("?>"));
  176. if (headerEnd.isEmpty())
  177. return false;
  178. #if JUCE_DEBUG
  179. auto encoding = String (input, headerEnd)
  180. .fromFirstOccurrenceOf ("encoding", false, true)
  181. .fromFirstOccurrenceOf ("=", false, false)
  182. .fromFirstOccurrenceOf ("\"", false, false)
  183. .upToFirstOccurrenceOf ("\"", false, false)
  184. .trim();
  185. /* If you load an XML document with a non-UTF encoding type, it may have been
  186. loaded wrongly.. Since all the files are read via the normal juce file streams,
  187. they're treated as UTF-8, so by the time it gets to the parser, the encoding will
  188. have been lost. Best plan is to stick to utf-8 or if you have specific files to
  189. read, use your own code to convert them to a unicode String, and pass that to the
  190. XML parser.
  191. */
  192. jassert (encoding.isEmpty() || encoding.startsWithIgnoreCase ("utf-"));
  193. #endif
  194. input = headerEnd + 2;
  195. skipNextWhiteSpace();
  196. }
  197. return true;
  198. }
  199. bool XmlDocument::parseDTD()
  200. {
  201. if (CharacterFunctions::compareUpTo (input, CharPointer_ASCII ("<!DOCTYPE"), 9) == 0)
  202. {
  203. input += 9;
  204. auto dtdStart = input;
  205. for (int n = 1; n > 0;)
  206. {
  207. auto c = readNextChar();
  208. if (outOfData)
  209. return false;
  210. if (c == '<')
  211. ++n;
  212. else if (c == '>')
  213. --n;
  214. }
  215. dtdText = String (dtdStart, input - 1).trim();
  216. }
  217. return true;
  218. }
  219. void XmlDocument::skipNextWhiteSpace()
  220. {
  221. for (;;)
  222. {
  223. input = input.findEndOfWhitespace();
  224. if (input.isEmpty())
  225. {
  226. outOfData = true;
  227. break;
  228. }
  229. if (*input == '<')
  230. {
  231. if (input[1] == '!'
  232. && input[2] == '-'
  233. && input[3] == '-')
  234. {
  235. input += 4;
  236. auto closeComment = input.indexOf (CharPointer_ASCII ("-->"));
  237. if (closeComment < 0)
  238. {
  239. outOfData = true;
  240. break;
  241. }
  242. input += closeComment + 3;
  243. continue;
  244. }
  245. if (input[1] == '?')
  246. {
  247. input += 2;
  248. auto closeBracket = input.indexOf (CharPointer_ASCII ("?>"));
  249. if (closeBracket < 0)
  250. {
  251. outOfData = true;
  252. break;
  253. }
  254. input += closeBracket + 2;
  255. continue;
  256. }
  257. }
  258. break;
  259. }
  260. }
  261. void XmlDocument::readQuotedString (String& result)
  262. {
  263. auto quote = readNextChar();
  264. while (! outOfData)
  265. {
  266. auto c = readNextChar();
  267. if (c == quote)
  268. break;
  269. --input;
  270. if (c == '&')
  271. {
  272. readEntity (result);
  273. }
  274. else
  275. {
  276. auto start = input;
  277. for (;;)
  278. {
  279. auto character = *input;
  280. if (character == quote)
  281. {
  282. result.appendCharPointer (start, input);
  283. ++input;
  284. return;
  285. }
  286. if (character == '&')
  287. {
  288. result.appendCharPointer (start, input);
  289. break;
  290. }
  291. if (character == 0)
  292. {
  293. setLastError ("unmatched quotes", false);
  294. outOfData = true;
  295. break;
  296. }
  297. ++input;
  298. }
  299. }
  300. }
  301. }
  302. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  303. {
  304. XmlElement* node = nullptr;
  305. skipNextWhiteSpace();
  306. if (outOfData)
  307. return nullptr;
  308. if (*input == '<')
  309. {
  310. ++input;
  311. auto endOfToken = XmlIdentifierChars::findEndOfToken (input);
  312. if (endOfToken == input)
  313. {
  314. // no tag name - but allow for a gap after the '<' before giving an error
  315. skipNextWhiteSpace();
  316. endOfToken = XmlIdentifierChars::findEndOfToken (input);
  317. if (endOfToken == input)
  318. {
  319. setLastError ("tag name missing", false);
  320. return node;
  321. }
  322. }
  323. node = new XmlElement (input, endOfToken);
  324. input = endOfToken;
  325. LinkedListPointer<XmlElement::XmlAttributeNode>::Appender attributeAppender (node->attributes);
  326. // look for attributes
  327. for (;;)
  328. {
  329. skipNextWhiteSpace();
  330. auto c = *input;
  331. // empty tag..
  332. if (c == '/' && input[1] == '>')
  333. {
  334. input += 2;
  335. break;
  336. }
  337. // parse the guts of the element..
  338. if (c == '>')
  339. {
  340. ++input;
  341. if (alsoParseSubElements)
  342. readChildElements (*node);
  343. break;
  344. }
  345. // get an attribute..
  346. if (XmlIdentifierChars::isIdentifierChar (c))
  347. {
  348. auto attNameEnd = XmlIdentifierChars::findEndOfToken (input);
  349. if (attNameEnd != input)
  350. {
  351. auto attNameStart = input;
  352. input = attNameEnd;
  353. skipNextWhiteSpace();
  354. if (readNextChar() == '=')
  355. {
  356. skipNextWhiteSpace();
  357. auto nextChar = *input;
  358. if (nextChar == '"' || nextChar == '\'')
  359. {
  360. auto* newAtt = new XmlElement::XmlAttributeNode (attNameStart, attNameEnd);
  361. readQuotedString (newAtt->value);
  362. attributeAppender.append (newAtt);
  363. continue;
  364. }
  365. }
  366. else
  367. {
  368. setLastError ("expected '=' after attribute '"
  369. + String (attNameStart, attNameEnd) + "'", false);
  370. return node;
  371. }
  372. }
  373. }
  374. else
  375. {
  376. if (! outOfData)
  377. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  378. }
  379. break;
  380. }
  381. }
  382. return node;
  383. }
  384. void XmlDocument::readChildElements (XmlElement& parent)
  385. {
  386. LinkedListPointer<XmlElement>::Appender childAppender (parent.firstChildElement);
  387. for (;;)
  388. {
  389. auto preWhitespaceInput = input;
  390. skipNextWhiteSpace();
  391. if (outOfData)
  392. {
  393. setLastError ("unmatched tags", false);
  394. break;
  395. }
  396. if (*input == '<')
  397. {
  398. auto c1 = input[1];
  399. if (c1 == '/')
  400. {
  401. // our close tag..
  402. auto closeTag = input.indexOf ((juce_wchar) '>');
  403. if (closeTag >= 0)
  404. input += closeTag + 1;
  405. break;
  406. }
  407. if (c1 == '!' && CharacterFunctions::compareUpTo (input + 2, CharPointer_ASCII ("[CDATA["), 7) == 0)
  408. {
  409. input += 9;
  410. auto inputStart = input;
  411. for (;;)
  412. {
  413. auto c0 = *input;
  414. if (c0 == 0)
  415. {
  416. setLastError ("unterminated CDATA section", false);
  417. outOfData = true;
  418. break;
  419. }
  420. if (c0 == ']' && input[1] == ']' && input[2] == '>')
  421. {
  422. childAppender.append (XmlElement::createTextElement (String (inputStart, input)));
  423. input += 3;
  424. break;
  425. }
  426. ++input;
  427. }
  428. }
  429. else
  430. {
  431. // this is some other element, so parse and add it..
  432. if (auto* n = readNextElement (true))
  433. childAppender.append (n);
  434. else
  435. break;
  436. }
  437. }
  438. else // must be a character block
  439. {
  440. input = preWhitespaceInput; // roll back to include the leading whitespace
  441. MemoryOutputStream textElementContent;
  442. bool contentShouldBeUsed = ! ignoreEmptyTextElements;
  443. for (;;)
  444. {
  445. auto c = *input;
  446. if (c == '<')
  447. {
  448. if (input[1] == '!' && input[2] == '-' && input[3] == '-')
  449. {
  450. input += 4;
  451. auto closeComment = input.indexOf (CharPointer_ASCII ("-->"));
  452. if (closeComment < 0)
  453. {
  454. setLastError ("unterminated comment", false);
  455. outOfData = true;
  456. return;
  457. }
  458. input += closeComment + 3;
  459. continue;
  460. }
  461. break;
  462. }
  463. if (c == 0)
  464. {
  465. setLastError ("unmatched tags", false);
  466. outOfData = true;
  467. return;
  468. }
  469. if (c == '&')
  470. {
  471. String entity;
  472. readEntity (entity);
  473. if (entity.startsWithChar ('<') && entity [1] != 0)
  474. {
  475. auto oldInput = input;
  476. auto oldOutOfData = outOfData;
  477. input = entity.getCharPointer();
  478. outOfData = false;
  479. while (auto* n = readNextElement (true))
  480. childAppender.append (n);
  481. input = oldInput;
  482. outOfData = oldOutOfData;
  483. }
  484. else
  485. {
  486. textElementContent << entity;
  487. contentShouldBeUsed = contentShouldBeUsed || entity.containsNonWhitespaceChars();
  488. }
  489. }
  490. else
  491. {
  492. for (;; ++input)
  493. {
  494. auto nextChar = *input;
  495. if (nextChar == '\r')
  496. {
  497. nextChar = '\n';
  498. if (input[1] == '\n')
  499. continue;
  500. }
  501. if (nextChar == '<' || nextChar == '&')
  502. break;
  503. if (nextChar == 0)
  504. {
  505. setLastError ("unmatched tags", false);
  506. outOfData = true;
  507. return;
  508. }
  509. textElementContent.appendUTF8Char (nextChar);
  510. contentShouldBeUsed = contentShouldBeUsed || ! CharacterFunctions::isWhitespace (nextChar);
  511. }
  512. }
  513. }
  514. if (contentShouldBeUsed)
  515. childAppender.append (XmlElement::createTextElement (textElementContent.toUTF8()));
  516. }
  517. }
  518. }
  519. void XmlDocument::readEntity (String& result)
  520. {
  521. // skip over the ampersand
  522. ++input;
  523. if (input.compareIgnoreCaseUpTo (CharPointer_ASCII ("amp;"), 4) == 0)
  524. {
  525. input += 4;
  526. result += '&';
  527. }
  528. else if (input.compareIgnoreCaseUpTo (CharPointer_ASCII ("quot;"), 5) == 0)
  529. {
  530. input += 5;
  531. result += '"';
  532. }
  533. else if (input.compareIgnoreCaseUpTo (CharPointer_ASCII ("apos;"), 5) == 0)
  534. {
  535. input += 5;
  536. result += '\'';
  537. }
  538. else if (input.compareIgnoreCaseUpTo (CharPointer_ASCII ("lt;"), 3) == 0)
  539. {
  540. input += 3;
  541. result += '<';
  542. }
  543. else if (input.compareIgnoreCaseUpTo (CharPointer_ASCII ("gt;"), 3) == 0)
  544. {
  545. input += 3;
  546. result += '>';
  547. }
  548. else if (*input == '#')
  549. {
  550. int charCode = 0;
  551. ++input;
  552. if (*input == 'x' || *input == 'X')
  553. {
  554. ++input;
  555. int numChars = 0;
  556. while (input[0] != ';')
  557. {
  558. auto hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  559. if (hexValue < 0 || ++numChars > 8)
  560. {
  561. setLastError ("illegal escape sequence", true);
  562. break;
  563. }
  564. charCode = (charCode << 4) | hexValue;
  565. ++input;
  566. }
  567. ++input;
  568. }
  569. else if (input[0] >= '0' && input[0] <= '9')
  570. {
  571. int numChars = 0;
  572. while (input[0] != ';')
  573. {
  574. if (++numChars > 12)
  575. {
  576. setLastError ("illegal escape sequence", true);
  577. break;
  578. }
  579. charCode = charCode * 10 + ((int) input[0] - '0');
  580. ++input;
  581. }
  582. ++input;
  583. }
  584. else
  585. {
  586. setLastError ("illegal escape sequence", true);
  587. result += '&';
  588. return;
  589. }
  590. result << (juce_wchar) charCode;
  591. }
  592. else
  593. {
  594. auto entityNameStart = input;
  595. auto closingSemiColon = input.indexOf ((juce_wchar) ';');
  596. if (closingSemiColon < 0)
  597. {
  598. outOfData = true;
  599. result += '&';
  600. }
  601. else
  602. {
  603. input += closingSemiColon + 1;
  604. result += expandExternalEntity (String (entityNameStart, (size_t) closingSemiColon));
  605. }
  606. }
  607. }
  608. String XmlDocument::expandEntity (const String& ent)
  609. {
  610. if (ent.equalsIgnoreCase ("amp")) return String::charToString ('&');
  611. if (ent.equalsIgnoreCase ("quot")) return String::charToString ('"');
  612. if (ent.equalsIgnoreCase ("apos")) return String::charToString ('\'');
  613. if (ent.equalsIgnoreCase ("lt")) return String::charToString ('<');
  614. if (ent.equalsIgnoreCase ("gt")) return String::charToString ('>');
  615. if (ent[0] == '#')
  616. {
  617. auto char1 = ent[1];
  618. if (char1 == 'x' || char1 == 'X')
  619. return String::charToString (static_cast<juce_wchar> (ent.substring (2).getHexValue32()));
  620. if (char1 >= '0' && char1 <= '9')
  621. return String::charToString (static_cast<juce_wchar> (ent.substring (1).getIntValue()));
  622. setLastError ("illegal escape sequence", false);
  623. return String::charToString ('&');
  624. }
  625. return expandExternalEntity (ent);
  626. }
  627. String XmlDocument::expandExternalEntity (const String& entity)
  628. {
  629. if (needToLoadDTD)
  630. {
  631. if (dtdText.isNotEmpty())
  632. {
  633. dtdText = dtdText.trimCharactersAtEnd (">");
  634. tokenisedDTD.addTokens (dtdText, true);
  635. if (tokenisedDTD[tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  636. && tokenisedDTD[tokenisedDTD.size() - 1].isQuotedString())
  637. {
  638. auto fn = tokenisedDTD[tokenisedDTD.size() - 1];
  639. tokenisedDTD.clear();
  640. tokenisedDTD.addTokens (getFileContents (fn), true);
  641. }
  642. else
  643. {
  644. tokenisedDTD.clear();
  645. auto openBracket = dtdText.indexOfChar ('[');
  646. if (openBracket > 0)
  647. {
  648. auto closeBracket = dtdText.lastIndexOfChar (']');
  649. if (closeBracket > openBracket)
  650. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  651. closeBracket), true);
  652. }
  653. }
  654. for (int i = tokenisedDTD.size(); --i >= 0;)
  655. {
  656. if (tokenisedDTD[i].startsWithChar ('%')
  657. && tokenisedDTD[i].endsWithChar (';'))
  658. {
  659. auto parsed = getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1));
  660. StringArray newToks;
  661. newToks.addTokens (parsed, true);
  662. tokenisedDTD.remove (i);
  663. for (int j = newToks.size(); --j >= 0;)
  664. tokenisedDTD.insert (i, newToks[j]);
  665. }
  666. }
  667. }
  668. needToLoadDTD = false;
  669. }
  670. for (int i = 0; i < tokenisedDTD.size(); ++i)
  671. {
  672. if (tokenisedDTD[i] == entity)
  673. {
  674. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  675. {
  676. auto ent = tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted();
  677. // check for sub-entities..
  678. auto ampersand = ent.indexOfChar ('&');
  679. while (ampersand >= 0)
  680. {
  681. auto semiColon = ent.indexOf (i + 1, ";");
  682. if (semiColon < 0)
  683. {
  684. setLastError ("entity without terminating semi-colon", false);
  685. break;
  686. }
  687. auto resolved = expandEntity (ent.substring (i + 1, semiColon));
  688. ent = ent.substring (0, ampersand)
  689. + resolved
  690. + ent.substring (semiColon + 1);
  691. ampersand = ent.indexOfChar (semiColon + 1, '&');
  692. }
  693. return ent;
  694. }
  695. }
  696. }
  697. setLastError ("unknown entity", true);
  698. return entity;
  699. }
  700. String XmlDocument::getParameterEntity (const String& entity)
  701. {
  702. for (int i = 0; i < tokenisedDTD.size(); ++i)
  703. {
  704. if (tokenisedDTD[i] == entity
  705. && tokenisedDTD [i - 1] == "%"
  706. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  707. {
  708. auto ent = tokenisedDTD [i + 1].trimCharactersAtEnd (">");
  709. if (ent.equalsIgnoreCase ("system"))
  710. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  711. return ent.trim().unquoted();
  712. }
  713. }
  714. return entity;
  715. }
  716. }