XMLFile.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Container/ArrayPtr.h"
  23. #include "../Core/Context.h"
  24. #include "../IO/Deserializer.h"
  25. #include "../IO/Log.h"
  26. #include "../IO/MemoryBuffer.h"
  27. #include "../Core/Profiler.h"
  28. #include "../Resource/ResourceCache.h"
  29. #include "../IO/Serializer.h"
  30. #include "../IO/VectorBuffer.h"
  31. #include "../Resource/XMLFile.h"
  32. #include <PugiXml/pugixml.hpp>
  33. #include "../DebugNew.h"
  34. namespace Urho3D
  35. {
  36. /// XML writer for pugixml.
  37. class XMLWriter : public pugi::xml_writer
  38. {
  39. public:
  40. /// Construct.
  41. XMLWriter(Serializer& dest) :
  42. dest_(dest),
  43. success_(true)
  44. {
  45. }
  46. /// Write bytes to output.
  47. void write(const void* data, size_t size)
  48. {
  49. if (dest_.Write(data, (unsigned)size) != size)
  50. success_ = false;
  51. }
  52. /// Destination serializer.
  53. Serializer& dest_;
  54. /// Success flag.
  55. bool success_;
  56. };
  57. XMLFile::XMLFile(Context* context) :
  58. Resource(context),
  59. document_(new pugi::xml_document())
  60. {
  61. }
  62. XMLFile::~XMLFile()
  63. {
  64. delete document_;
  65. document_ = 0;
  66. }
  67. void XMLFile::RegisterObject(Context* context)
  68. {
  69. context->RegisterFactory<XMLFile>();
  70. }
  71. bool XMLFile::BeginLoad(Deserializer& source)
  72. {
  73. unsigned dataSize = source.GetSize();
  74. if (!dataSize && !source.GetName().Empty())
  75. {
  76. LOGERROR("Zero sized XML data in " + source.GetName());
  77. return false;
  78. }
  79. SharedArrayPtr<char> buffer(new char[dataSize]);
  80. if (source.Read(buffer.Get(), dataSize) != dataSize)
  81. return false;
  82. if (!document_->load_buffer(buffer.Get(), dataSize))
  83. {
  84. LOGERROR("Could not parse XML data from " + source.GetName());
  85. document_->reset();
  86. return false;
  87. }
  88. XMLElement rootElem = GetRoot();
  89. String inherit = rootElem.GetAttribute("inherit");
  90. if (!inherit.Empty())
  91. {
  92. // The existence of this attribute indicates this is an RFC 5261 patch file
  93. ResourceCache* cache = GetSubsystem<ResourceCache>();
  94. // If being async loaded, GetResource() is not safe, so use GetTempResource() instead
  95. XMLFile* inheritedXMLFile = GetAsyncLoadState() == ASYNC_DONE ? cache->GetResource<XMLFile>(inherit) :
  96. cache->GetTempResource<XMLFile>(inherit);
  97. if (!inheritedXMLFile)
  98. {
  99. LOGERRORF("Could not find inherited XML file: %s", inherit.CString());
  100. return false;
  101. }
  102. // Patch this XMLFile and leave the original inherited XMLFile as it is
  103. pugi::xml_document* patchDocument = document_;
  104. document_ = new pugi::xml_document();
  105. document_->reset(*inheritedXMLFile->document_);
  106. Patch(rootElem);
  107. delete patchDocument;
  108. // Store resource dependencies so we know when to reload/repatch when the inherited resource changes
  109. cache->StoreResourceDependency(this, inherit);
  110. // Approximate patched data size
  111. dataSize += inheritedXMLFile->GetMemoryUse();
  112. }
  113. // Note: this probably does not reflect internal data structure size accurately
  114. SetMemoryUse(dataSize);
  115. return true;
  116. }
  117. bool XMLFile::Save(Serializer& dest) const
  118. {
  119. return Save(dest, "\t");
  120. }
  121. bool XMLFile::Save(Serializer& dest, const String& indendation) const
  122. {
  123. XMLWriter writer(dest);
  124. document_->save(writer, indendation.CString());
  125. return writer.success_;
  126. }
  127. XMLElement XMLFile::CreateRoot(const String& name)
  128. {
  129. document_->reset();
  130. pugi::xml_node root = document_->append_child(name.CString());
  131. return XMLElement(this, root.internal_object());
  132. }
  133. bool XMLFile::FromString(const String& source)
  134. {
  135. if (source.Empty())
  136. return false;
  137. MemoryBuffer buffer(source.CString(), source.Length());
  138. return Load(buffer);
  139. }
  140. XMLElement XMLFile::GetRoot(const String& name)
  141. {
  142. pugi::xml_node root = document_->first_child();
  143. if (root.empty())
  144. return XMLElement();
  145. if (!name.Empty() && name != root.name())
  146. return XMLElement();
  147. else
  148. return XMLElement(this, root.internal_object());
  149. }
  150. String XMLFile::ToString(const String& indendation) const
  151. {
  152. VectorBuffer dest;
  153. XMLWriter writer(dest);
  154. document_->save(writer, indendation.CString());
  155. return String((const char*)dest.GetData(), dest.GetSize());
  156. }
  157. void XMLFile::Patch(XMLFile* patchFile)
  158. {
  159. Patch(patchFile->GetRoot());
  160. }
  161. void XMLFile::Patch(XMLElement patchElement)
  162. {
  163. pugi::xml_node root = pugi::xml_node(patchElement.GetNode());
  164. for (pugi::xml_node::iterator patch = root.begin(); patch != root.end(); patch++)
  165. {
  166. pugi::xml_attribute sel = patch->attribute("sel");
  167. if (sel.empty())
  168. {
  169. LOGERROR("XML Patch failed due to node not having a sel attribute.");
  170. continue;
  171. }
  172. // Only select a single node at a time, they can use xpath to select specific ones in multiple otherwise the node set becomes invalid due to changes
  173. pugi::xpath_node original = document_->select_single_node(sel.value());
  174. if (!original)
  175. {
  176. LOGERRORF("XML Patch failed with bad select: %s.", sel.value());
  177. continue;
  178. }
  179. if (strcmp(patch->name(),"add") == 0)
  180. PatchAdd(*patch, original);
  181. else if (strcmp(patch->name(), "replace") == 0)
  182. PatchReplace(*patch, original);
  183. else if (strcmp(patch->name(), "remove") == 0)
  184. PatchRemove(original);
  185. else
  186. LOGERROR("XMLFiles used for patching should only use 'add', 'replace' or 'remove' elements.");
  187. }
  188. }
  189. void XMLFile::PatchAdd(const pugi::xml_node& patch, pugi::xpath_node& original)
  190. {
  191. // If not a node, log an error
  192. if (original.attribute())
  193. {
  194. LOGERRORF("XML Patch failed calling Add due to not selecting a node, %s attribute was selected.", original.attribute().name());
  195. return;
  196. }
  197. // If no type add node, if contains '@' treat as attribute
  198. pugi::xml_attribute type = patch.attribute("type");
  199. if (!type || strlen(type.value()) <= 0)
  200. AddNode(patch, original);
  201. else if (type.value()[0] == '@')
  202. AddAttribute(patch, original);
  203. }
  204. void XMLFile::PatchReplace(const pugi::xml_node& patch, pugi::xpath_node& original)
  205. {
  206. // If no attribute but node then its a node, otherwise its an attribute or null
  207. if (!original.attribute() && original.node())
  208. {
  209. pugi::xml_node parent = original.node().parent();
  210. parent.insert_copy_before(patch.first_child(), original.node());
  211. parent.remove_child(original.node());
  212. }
  213. else if (original.attribute())
  214. {
  215. original.attribute().set_value(patch.child_value());
  216. }
  217. }
  218. void XMLFile::PatchRemove(const pugi::xpath_node& original)
  219. {
  220. // If no attribute but node then its a node, otherwise its an attribute or null
  221. if (!original.attribute() && original.node())
  222. {
  223. pugi::xml_node parent = original.parent();
  224. parent.remove_child(original.node());
  225. }
  226. else if (original.attribute())
  227. {
  228. pugi::xml_node parent = original.parent();
  229. parent.remove_attribute(original.attribute());
  230. }
  231. }
  232. void XMLFile::AddNode(const pugi::xml_node& patch, pugi::xpath_node& original)
  233. {
  234. // If pos is null, append or prepend add as a child, otherwise add before or after, the default is to append as a child
  235. pugi::xml_attribute pos = patch.attribute("pos");
  236. if (!pos || strlen(pos.value()) <= 0 || strcmp(pos.value(), "append") == 0)
  237. {
  238. pugi::xml_node::iterator start = patch.begin();
  239. pugi::xml_node::iterator end = patch.end();
  240. // There can not be two consecutive text nodes, so check to see if they need to be combined
  241. // If they have been we can skip the first node of the nodes to add
  242. if (CombineText(patch.first_child(), original.node().last_child(), false))
  243. start++;
  244. for (; start != end; start++)
  245. original.node().append_copy(*start);
  246. }
  247. else if (strcmp(pos.value(), "prepend") == 0)
  248. {
  249. pugi::xml_node::iterator start = patch.begin();
  250. pugi::xml_node::iterator end = patch.end();
  251. // There can not be two consecutive text nodes, so check to see if they need to be combined
  252. // If they have been we can skip the last node of the nodes to add
  253. if (CombineText(patch.last_child(), original.node().first_child(), true))
  254. end--;
  255. pugi::xml_node pos = original.node().first_child();
  256. for (; start != end; start++)
  257. original.node().insert_copy_before(*start, pos);
  258. }
  259. else if (strcmp(pos.value(), "before") == 0)
  260. {
  261. pugi::xml_node::iterator start = patch.begin();
  262. pugi::xml_node::iterator end = patch.end();
  263. // There can not be two consecutive text nodes, so check to see if they need to be combined
  264. // If they have been we can skip the first node of the nodes to add
  265. if (CombineText(patch.first_child(), original.node().previous_sibling(), false))
  266. start++;
  267. // There can not be two consecutive text nodes, so check to see if they need to be combined
  268. // If they have been we can skip the last node of the nodes to add
  269. if (CombineText(patch.last_child(), original.node(), true))
  270. end--;
  271. for (; start != end; start++)
  272. original.parent().insert_copy_before(*start, original.node());
  273. }
  274. else if (strcmp(pos.value(), "after") == 0)
  275. {
  276. pugi::xml_node::iterator start = patch.begin();
  277. pugi::xml_node::iterator end = patch.end();
  278. // There can not be two consecutive text nodes, so check to see if they need to be combined
  279. // If they have been we can skip the first node of the nodes to add
  280. if (CombineText(patch.first_child(), original.node(), false))
  281. start++;
  282. // There can not be two consecutive text nodes, so check to see if they need to be combined
  283. // If they have been we can skip the last node of the nodes to add
  284. if (CombineText(patch.last_child(), original.node().next_sibling(), true))
  285. end--;
  286. pugi::xml_node pos = original.node();
  287. for (; start != end; start++)
  288. pos = original.parent().insert_copy_after(*start, pos);
  289. }
  290. }
  291. void XMLFile::AddAttribute(const pugi::xml_node& patch, pugi::xpath_node& original)
  292. {
  293. pugi::xml_attribute attribute = patch.attribute("type");
  294. if (!patch.first_child() && patch.first_child().type() != pugi::node_pcdata)
  295. {
  296. LOGERRORF("XML Patch failed calling Add due to attempting to add non text to an attribute for %s.", attribute.value());
  297. return;
  298. }
  299. String name(attribute.value());
  300. name = name.Substring(1);
  301. pugi::xml_attribute newAttribute = original.node().append_attribute(name.CString());
  302. newAttribute.set_value(patch.child_value());
  303. }
  304. bool XMLFile::CombineText(const pugi::xml_node& patch, pugi::xml_node original, bool prepend)
  305. {
  306. if (!patch || !original)
  307. return false;
  308. if ((patch.type() == pugi::node_pcdata && original.type() == pugi::node_pcdata) ||
  309. (patch.type() == pugi::node_cdata && original.type() == pugi::node_cdata))
  310. {
  311. if (prepend)
  312. original.set_value(Urho3D::ToString("%s%s", patch.value(), original.value()).CString());
  313. else
  314. original.set_value(Urho3D::ToString("%s%s", original.value(), patch.value()).CString());
  315. return true;
  316. }
  317. return false;
  318. }
  319. }