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.

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