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.

854 lines
24KB

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