xml_parser.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. /*************************************************************************/
  2. /* xml_parser.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "xml_parser.h"
  31. #include "core/print_string.h"
  32. //#define DEBUG_XML
  33. VARIANT_ENUM_CAST(XMLParser::NodeType);
  34. static bool _equalsn(const CharType *str1, const CharType *str2, int len) {
  35. int i;
  36. for (i = 0; i < len && str1[i] && str2[i]; ++i) {
  37. if (str1[i] != str2[i]) {
  38. return false;
  39. }
  40. }
  41. // if one (or both) of the strings was smaller then they
  42. // are only equal if they have the same length
  43. return (i == len) || (str1[i] == 0 && str2[i] == 0);
  44. }
  45. String XMLParser::_replace_special_characters(const String &origstr) {
  46. int pos = origstr.find("&");
  47. int oldPos = 0;
  48. if (pos == -1) {
  49. return origstr;
  50. }
  51. String newstr;
  52. while (pos != -1 && pos < origstr.length() - 2) {
  53. // check if it is one of the special characters
  54. int specialChar = -1;
  55. for (int i = 0; i < (int)special_characters.size(); ++i) {
  56. const CharType *p = &origstr[pos] + 1;
  57. if (_equalsn(&special_characters[i][1], p, special_characters[i].length() - 1)) {
  58. specialChar = i;
  59. break;
  60. }
  61. }
  62. if (specialChar != -1) {
  63. newstr += (origstr.substr(oldPos, pos - oldPos));
  64. newstr += (special_characters[specialChar][0]);
  65. pos += special_characters[specialChar].length();
  66. } else {
  67. newstr += (origstr.substr(oldPos, pos - oldPos + 1));
  68. pos += 1;
  69. }
  70. // find next &
  71. oldPos = pos;
  72. pos = origstr.find("&", pos);
  73. }
  74. if (oldPos < origstr.length() - 1) {
  75. newstr += (origstr.substr(oldPos, origstr.length() - oldPos));
  76. }
  77. return newstr;
  78. }
  79. static inline bool _is_white_space(char c) {
  80. return (c == ' ' || c == '\t' || c == '\n' || c == '\r');
  81. }
  82. //! sets the state that text was found. Returns true if set should be set
  83. bool XMLParser::_set_text(char *start, char *end) {
  84. // check if text is more than 2 characters, and if not, check if there is
  85. // only white space, so that this text won't be reported
  86. if (end - start < 3) {
  87. char *p = start;
  88. for (; p != end; ++p) {
  89. if (!_is_white_space(*p)) {
  90. break;
  91. }
  92. }
  93. if (p == end) {
  94. return false;
  95. }
  96. }
  97. // set current text to the parsed text, and replace xml special characters
  98. String s = String::utf8(start, (int)(end - start));
  99. node_name = _replace_special_characters(s);
  100. // current XML node type is text
  101. node_type = NODE_TEXT;
  102. return true;
  103. }
  104. void XMLParser::_parse_closing_xml_element() {
  105. node_type = NODE_ELEMENT_END;
  106. node_empty = false;
  107. attributes.clear();
  108. ++P;
  109. const char *pBeginClose = P;
  110. while (*P != '>') {
  111. ++P;
  112. }
  113. node_name = String::utf8(pBeginClose, (int)(P - pBeginClose));
  114. #ifdef DEBUG_XML
  115. print_line("XML CLOSE: " + node_name);
  116. #endif
  117. ++P;
  118. }
  119. void XMLParser::_ignore_definition() {
  120. node_type = NODE_UNKNOWN;
  121. char *F = P;
  122. // move until end marked with '>' reached
  123. while (*P != '>') {
  124. ++P;
  125. }
  126. node_name.parse_utf8(F, P - F);
  127. ++P;
  128. }
  129. bool XMLParser::_parse_cdata() {
  130. if (*(P + 1) != '[') {
  131. return false;
  132. }
  133. node_type = NODE_CDATA;
  134. // skip '<![CDATA['
  135. int count = 0;
  136. while (*P && count < 8) {
  137. ++P;
  138. ++count;
  139. }
  140. if (!*P) {
  141. return true;
  142. }
  143. char *cDataBegin = P;
  144. char *cDataEnd = nullptr;
  145. // find end of CDATA
  146. while (*P && !cDataEnd) {
  147. if (*P == '>' &&
  148. (*(P - 1) == ']') &&
  149. (*(P - 2) == ']')) {
  150. cDataEnd = P - 2;
  151. }
  152. ++P;
  153. }
  154. if (cDataEnd) {
  155. node_name = String::utf8(cDataBegin, (int)(cDataEnd - cDataBegin));
  156. } else {
  157. node_name = "";
  158. }
  159. #ifdef DEBUG_XML
  160. print_line("XML CDATA: " + node_name);
  161. #endif
  162. return true;
  163. }
  164. void XMLParser::_parse_comment() {
  165. node_type = NODE_COMMENT;
  166. P += 1;
  167. char *pCommentBegin = P;
  168. int count = 1;
  169. // move until end of comment reached
  170. while (count) {
  171. if (*P == '>') {
  172. --count;
  173. } else if (*P == '<') {
  174. ++count;
  175. }
  176. ++P;
  177. }
  178. P -= 3;
  179. node_name = String::utf8(pCommentBegin + 2, (int)(P - pCommentBegin - 2));
  180. P += 3;
  181. #ifdef DEBUG_XML
  182. print_line("XML COMMENT: " + node_name);
  183. #endif
  184. }
  185. void XMLParser::_parse_opening_xml_element() {
  186. node_type = NODE_ELEMENT;
  187. node_empty = false;
  188. attributes.clear();
  189. // find name
  190. const char *startName = P;
  191. // find end of element
  192. while (*P != '>' && !_is_white_space(*P)) {
  193. ++P;
  194. }
  195. const char *endName = P;
  196. // find attributes
  197. while (*P != '>') {
  198. if (_is_white_space(*P)) {
  199. ++P;
  200. } else {
  201. if (*P != '/') {
  202. // we've got an attribute
  203. // read the attribute names
  204. const char *attributeNameBegin = P;
  205. while (!_is_white_space(*P) && *P != '=') {
  206. ++P;
  207. }
  208. const char *attributeNameEnd = P;
  209. ++P;
  210. // read the attribute value
  211. // check for quotes and single quotes, thx to murphy
  212. while ((*P != '\"') && (*P != '\'') && *P) {
  213. ++P;
  214. }
  215. if (!*P) { // malformatted xml file
  216. return;
  217. }
  218. const char attributeQuoteChar = *P;
  219. ++P;
  220. const char *attributeValueBegin = P;
  221. while (*P != attributeQuoteChar && *P) {
  222. ++P;
  223. }
  224. if (!*P) { // malformatted xml file
  225. return;
  226. }
  227. const char *attributeValueEnd = P;
  228. ++P;
  229. Attribute attr;
  230. attr.name = String::utf8(attributeNameBegin,
  231. (int)(attributeNameEnd - attributeNameBegin));
  232. String s = String::utf8(attributeValueBegin,
  233. (int)(attributeValueEnd - attributeValueBegin));
  234. attr.value = _replace_special_characters(s);
  235. attributes.push_back(attr);
  236. } else {
  237. // tag is closed directly
  238. ++P;
  239. node_empty = true;
  240. break;
  241. }
  242. }
  243. }
  244. // check if this tag is closing directly
  245. if (endName > startName && *(endName - 1) == '/') {
  246. // directly closing tag
  247. node_empty = true;
  248. endName--;
  249. }
  250. node_name = String::utf8(startName, (int)(endName - startName));
  251. #ifdef DEBUG_XML
  252. print_line("XML OPEN: " + node_name);
  253. #endif
  254. ++P;
  255. }
  256. void XMLParser::_parse_current_node() {
  257. char *start = P;
  258. node_offset = P - data;
  259. // more forward until '<' found
  260. while (*P != '<' && *P) {
  261. ++P;
  262. }
  263. if (!*P) {
  264. return;
  265. }
  266. if (P - start > 0) {
  267. // we found some text, store it
  268. if (_set_text(start, P)) {
  269. return;
  270. }
  271. }
  272. ++P;
  273. // based on current token, parse and report next element
  274. switch (*P) {
  275. case '/':
  276. _parse_closing_xml_element();
  277. break;
  278. case '?':
  279. _ignore_definition();
  280. break;
  281. case '!':
  282. if (!_parse_cdata()) {
  283. _parse_comment();
  284. }
  285. break;
  286. default:
  287. _parse_opening_xml_element();
  288. break;
  289. }
  290. }
  291. uint64_t XMLParser::get_node_offset() const {
  292. return node_offset;
  293. };
  294. Error XMLParser::seek(uint64_t p_pos) {
  295. ERR_FAIL_COND_V(!data, ERR_FILE_EOF);
  296. ERR_FAIL_COND_V(p_pos >= length, ERR_FILE_EOF);
  297. P = data + p_pos;
  298. return read();
  299. };
  300. void XMLParser::_bind_methods() {
  301. ClassDB::bind_method(D_METHOD("read"), &XMLParser::read);
  302. ClassDB::bind_method(D_METHOD("get_node_type"), &XMLParser::get_node_type);
  303. ClassDB::bind_method(D_METHOD("get_node_name"), &XMLParser::get_node_name);
  304. ClassDB::bind_method(D_METHOD("get_node_data"), &XMLParser::get_node_data);
  305. ClassDB::bind_method(D_METHOD("get_node_offset"), &XMLParser::get_node_offset);
  306. ClassDB::bind_method(D_METHOD("get_attribute_count"), &XMLParser::get_attribute_count);
  307. ClassDB::bind_method(D_METHOD("get_attribute_name", "idx"), &XMLParser::get_attribute_name);
  308. ClassDB::bind_method(D_METHOD("get_attribute_value", "idx"), (String(XMLParser::*)(int) const) & XMLParser::get_attribute_value);
  309. ClassDB::bind_method(D_METHOD("has_attribute", "name"), &XMLParser::has_attribute);
  310. ClassDB::bind_method(D_METHOD("get_named_attribute_value", "name"), (String(XMLParser::*)(const String &) const) & XMLParser::get_attribute_value);
  311. ClassDB::bind_method(D_METHOD("get_named_attribute_value_safe", "name"), &XMLParser::get_attribute_value_safe);
  312. ClassDB::bind_method(D_METHOD("is_empty"), &XMLParser::is_empty);
  313. ClassDB::bind_method(D_METHOD("get_current_line"), &XMLParser::get_current_line);
  314. ClassDB::bind_method(D_METHOD("skip_section"), &XMLParser::skip_section);
  315. ClassDB::bind_method(D_METHOD("seek", "position"), &XMLParser::seek);
  316. ClassDB::bind_method(D_METHOD("open", "file"), &XMLParser::open);
  317. ClassDB::bind_method(D_METHOD("open_buffer", "buffer"), &XMLParser::open_buffer);
  318. BIND_ENUM_CONSTANT(NODE_NONE);
  319. BIND_ENUM_CONSTANT(NODE_ELEMENT);
  320. BIND_ENUM_CONSTANT(NODE_ELEMENT_END);
  321. BIND_ENUM_CONSTANT(NODE_TEXT);
  322. BIND_ENUM_CONSTANT(NODE_COMMENT);
  323. BIND_ENUM_CONSTANT(NODE_CDATA);
  324. BIND_ENUM_CONSTANT(NODE_UNKNOWN);
  325. };
  326. Error XMLParser::read() {
  327. // if not end reached, parse the node
  328. if (P && (P - data) < (int64_t)length - 1 && *P != 0) {
  329. _parse_current_node();
  330. return OK;
  331. }
  332. return ERR_FILE_EOF;
  333. }
  334. XMLParser::NodeType XMLParser::get_node_type() {
  335. return node_type;
  336. }
  337. String XMLParser::get_node_data() const {
  338. ERR_FAIL_COND_V(node_type != NODE_TEXT, "");
  339. return node_name;
  340. }
  341. String XMLParser::get_node_name() const {
  342. ERR_FAIL_COND_V(node_type == NODE_TEXT, "");
  343. return node_name;
  344. }
  345. int XMLParser::get_attribute_count() const {
  346. return attributes.size();
  347. }
  348. String XMLParser::get_attribute_name(int p_idx) const {
  349. ERR_FAIL_INDEX_V(p_idx, attributes.size(), "");
  350. return attributes[p_idx].name;
  351. }
  352. String XMLParser::get_attribute_value(int p_idx) const {
  353. ERR_FAIL_INDEX_V(p_idx, attributes.size(), "");
  354. return attributes[p_idx].value;
  355. }
  356. bool XMLParser::has_attribute(const String &p_name) const {
  357. for (int i = 0; i < attributes.size(); i++) {
  358. if (attributes[i].name == p_name) {
  359. return true;
  360. }
  361. }
  362. return false;
  363. }
  364. String XMLParser::get_attribute_value(const String &p_name) const {
  365. int idx = -1;
  366. for (int i = 0; i < attributes.size(); i++) {
  367. if (attributes[i].name == p_name) {
  368. idx = i;
  369. break;
  370. }
  371. }
  372. ERR_FAIL_COND_V_MSG(idx < 0, "", "Attribute not found: " + p_name + ".");
  373. return attributes[idx].value;
  374. }
  375. String XMLParser::get_attribute_value_safe(const String &p_name) const {
  376. int idx = -1;
  377. for (int i = 0; i < attributes.size(); i++) {
  378. if (attributes[i].name == p_name) {
  379. idx = i;
  380. break;
  381. }
  382. }
  383. if (idx < 0) {
  384. return "";
  385. }
  386. return attributes[idx].value;
  387. }
  388. bool XMLParser::is_empty() const {
  389. return node_empty;
  390. }
  391. Error XMLParser::open_buffer(const Vector<uint8_t> &p_buffer) {
  392. ERR_FAIL_COND_V(p_buffer.size() == 0, ERR_INVALID_DATA);
  393. if (data) {
  394. memdelete_arr(data);
  395. }
  396. length = p_buffer.size();
  397. data = memnew_arr(char, length + 1);
  398. copymem(data, p_buffer.ptr(), length);
  399. data[length] = 0;
  400. P = data;
  401. return OK;
  402. }
  403. Error XMLParser::open(const String &p_path) {
  404. Error err;
  405. FileAccess *file = FileAccess::open(p_path, FileAccess::READ, &err);
  406. ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot open file '" + p_path + "'.");
  407. length = file->get_len();
  408. ERR_FAIL_COND_V(length < 1, ERR_FILE_CORRUPT);
  409. if (data) {
  410. memdelete_arr(data);
  411. }
  412. data = memnew_arr(char, length + 1);
  413. file->get_buffer((uint8_t *)data, length);
  414. data[length] = 0;
  415. P = data;
  416. memdelete(file);
  417. return OK;
  418. }
  419. void XMLParser::skip_section() {
  420. // skip if this element is empty anyway.
  421. if (is_empty()) {
  422. return;
  423. }
  424. // read until we've reached the last element in this section
  425. int tagcount = 1;
  426. while (tagcount && read() == OK) {
  427. if (get_node_type() == XMLParser::NODE_ELEMENT &&
  428. !is_empty()) {
  429. ++tagcount;
  430. } else if (get_node_type() == XMLParser::NODE_ELEMENT_END) {
  431. --tagcount;
  432. }
  433. }
  434. }
  435. void XMLParser::close() {
  436. if (data) {
  437. memdelete_arr(data);
  438. }
  439. data = nullptr;
  440. length = 0;
  441. P = nullptr;
  442. node_empty = false;
  443. node_type = NODE_NONE;
  444. node_offset = 0;
  445. }
  446. int XMLParser::get_current_line() const {
  447. return 0;
  448. }
  449. XMLParser::XMLParser() {
  450. special_characters.push_back("&amp;");
  451. special_characters.push_back("<lt;");
  452. special_characters.push_back(">gt;");
  453. special_characters.push_back("\"quot;");
  454. special_characters.push_back("'apos;");
  455. }
  456. XMLParser::~XMLParser() {
  457. if (data) {
  458. memdelete_arr(data);
  459. }
  460. }