XMLFile.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. //
  2. // Copyright (c) 2008-2014 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 "Precompiled.h"
  23. #include "ArrayPtr.h"
  24. #include "Context.h"
  25. #include "Deserializer.h"
  26. #include "Log.h"
  27. #include "Profiler.h"
  28. #include "ResourceCache.h"
  29. #include "Serializer.h"
  30. #include "XMLFile.h"
  31. #include <pugixml.hpp>
  32. #include "DebugNew.h"
  33. namespace Urho3D
  34. {
  35. /// XML writer for pugixml.
  36. class XMLWriter : public pugi::xml_writer
  37. {
  38. public:
  39. /// Construct.
  40. XMLWriter(Serializer& dest) :
  41. dest_(dest),
  42. success_(true)
  43. {
  44. }
  45. /// Write bytes to output.
  46. void write(const void* data, size_t size)
  47. {
  48. if (dest_.Write(data, size) != size)
  49. success_ = false;
  50. }
  51. /// Destination serializer.
  52. Serializer& dest_;
  53. /// Success flag.
  54. bool success_;
  55. };
  56. XMLFile::XMLFile(Context* context) :
  57. Resource(context),
  58. document_(new pugi::xml_document())
  59. {
  60. }
  61. XMLFile::~XMLFile()
  62. {
  63. delete document_;
  64. document_ = 0;
  65. }
  66. void XMLFile::RegisterObject(Context* context)
  67. {
  68. context->RegisterFactory<XMLFile>();
  69. }
  70. bool XMLFile::Load(Deserializer& source)
  71. {
  72. PROFILE(LoadXMLFile);
  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. return false;
  86. }
  87. XMLElement rootElem = GetRoot();
  88. String inherit = rootElem.GetAttribute("inherit");
  89. if (!inherit.Empty())
  90. {
  91. // The existence of this attribute indicates this is an RFC 5261 patch file
  92. ResourceCache* cache = GetSubsystem<ResourceCache>();
  93. XMLFile* inheritedXMLFile = cache->GetResource<XMLFile>(inherit);
  94. if (!inheritedXMLFile)
  95. {
  96. LOGERRORF("Could not find inherited XML file: %s", inherit.CString());
  97. return false;
  98. }
  99. // Patch this XMLFile and leave the original inherited XMLFile as it is
  100. pugi::xml_document* patchDocument = document_;
  101. document_ = new pugi::xml_document();
  102. document_->reset(*inheritedXMLFile->document_);
  103. Patch(rootElem);
  104. delete patchDocument;
  105. // Store resource dependencies so we know when to reload/repatch when the inherited resource changes
  106. cache->StoreResourceDependency(this, inherit);
  107. // Approximate patched data size
  108. dataSize += inheritedXMLFile->GetMemoryUse();
  109. }
  110. // Note: this probably does not reflect internal data structure size accurately
  111. SetMemoryUse(dataSize);
  112. return true;
  113. }
  114. bool XMLFile::Save(Serializer& dest) const
  115. {
  116. XMLWriter writer(dest);
  117. document_->save(writer);
  118. return writer.success_;
  119. }
  120. XMLElement XMLFile::CreateRoot(const String& name)
  121. {
  122. document_->reset();
  123. pugi::xml_node root = document_->append_child(name.CString());
  124. return XMLElement(this, root.internal_object());
  125. }
  126. XMLElement XMLFile::GetRoot(const String& name)
  127. {
  128. pugi::xml_node root = document_->first_child();
  129. if (root.empty())
  130. return XMLElement();
  131. if (!name.Empty() && name != root.name())
  132. return XMLElement();
  133. else
  134. return XMLElement(this, root.internal_object());
  135. }
  136. void XMLFile::Patch(XMLFile* patchFile)
  137. {
  138. Patch(patchFile->GetRoot());
  139. }
  140. void XMLFile::Patch(XMLElement patchElement)
  141. {
  142. pugi::xml_node root = pugi::xml_node(patchElement.GetNode());
  143. for (pugi::xml_node::iterator patch = root.begin(); patch != root.end(); patch++)
  144. {
  145. pugi::xml_attribute sel = patch->attribute("sel");
  146. if (sel.empty())
  147. {
  148. LOGERROR("XML Patch failed due to node not having a sel attribute.");
  149. continue;
  150. }
  151. // 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
  152. pugi::xpath_node original = document_->select_single_node(sel.value());
  153. if (!original)
  154. {
  155. LOGERRORF("XML Patch failed with bad select: %s.", sel.value());
  156. continue;
  157. }
  158. if (strcmp(patch->name(),"add") == 0)
  159. PatchAdd(*patch, original);
  160. else if (strcmp(patch->name(), "replace") == 0)
  161. PatchReplace(*patch, original);
  162. else if (strcmp(patch->name(), "remove") == 0)
  163. PatchRemove(original);
  164. else
  165. LOGERROR("XMLFiles used for patching should only use 'add', 'replace' or 'remove' elements.");
  166. }
  167. }
  168. void XMLFile::PatchAdd(const pugi::xml_node& patch, pugi::xpath_node& original)
  169. {
  170. // If not a node, log an error
  171. if (original.attribute())
  172. {
  173. LOGERRORF("XML Patch failed calling Add due to not selecting a node, %s attribute was selected.", original.attribute().name());
  174. return;
  175. }
  176. // If no type add node, if contains '@' treat as attribute
  177. pugi::xml_attribute type = patch.attribute("type");
  178. if (!type || strlen(type.value()) <= 0)
  179. AddNode(patch, original);
  180. else if (type.value()[0] == '@')
  181. AddAttribute(patch, original);
  182. }
  183. void XMLFile::PatchReplace(const pugi::xml_node& patch, pugi::xpath_node& original)
  184. {
  185. // If no attribute but node then its a node, otherwise its an attribute or null
  186. if (!original.attribute() && original.node())
  187. {
  188. pugi::xml_node parent = original.node().parent();
  189. parent.insert_copy_before(patch.first_child(), original.node());
  190. parent.remove_child(original.node());
  191. }
  192. else if (original.attribute())
  193. {
  194. original.attribute().set_value(patch.child_value());
  195. }
  196. }
  197. void XMLFile::PatchRemove(const pugi::xpath_node& original)
  198. {
  199. // If no attribute but node then its a node, otherwise its an attribute or null
  200. if (!original.attribute() && original.node())
  201. {
  202. pugi::xml_node parent = original.parent();
  203. parent.remove_child(original.node());
  204. }
  205. else if (original.attribute())
  206. {
  207. pugi::xml_node parent = original.parent();
  208. parent.remove_attribute(original.attribute());
  209. }
  210. }
  211. void XMLFile::AddNode(const pugi::xml_node& patch, pugi::xpath_node& original)
  212. {
  213. // If pos is null, append or prepend add as a child, otherwise add before or after, the default is to append as a child
  214. pugi::xml_attribute pos = patch.attribute("pos");
  215. if (!pos || strlen(pos.value()) <= 0 || pos.value() == "append")
  216. {
  217. pugi::xml_node::iterator start = patch.begin();
  218. pugi::xml_node::iterator end = patch.end();
  219. // There can not be two consecutive text nodes, so check to see if they need to be combined
  220. // If they have been we can skip the first node of the nodes to add
  221. if (CombineText(patch.first_child(), original.node().last_child(), false))
  222. start++;
  223. for (; start != end; start++)
  224. original.node().append_copy(*start);
  225. }
  226. else if (strcmp(pos.value(), "prepend") == 0)
  227. {
  228. pugi::xml_node::iterator start = patch.begin();
  229. pugi::xml_node::iterator end = patch.end();
  230. // There can not be two consecutive text nodes, so check to see if they need to be combined
  231. // If they have been we can skip the last node of the nodes to add
  232. if (CombineText(patch.last_child(), original.node().first_child(), true))
  233. end--;
  234. pugi::xml_node pos = original.node().first_child();
  235. for (; start != end; start++)
  236. original.node().insert_copy_before(*start, pos);
  237. }
  238. else if (strcmp(pos.value(), "before") == 0)
  239. {
  240. pugi::xml_node::iterator start = patch.begin();
  241. pugi::xml_node::iterator end = patch.end();
  242. // There can not be two consecutive text nodes, so check to see if they need to be combined
  243. // If they have been we can skip the first node of the nodes to add
  244. if (CombineText(patch.first_child(), original.node().previous_sibling(), false))
  245. start++;
  246. // There can not be two consecutive text nodes, so check to see if they need to be combined
  247. // If they have been we can skip the last node of the nodes to add
  248. if (CombineText(patch.last_child(), original.node(), true))
  249. end--;
  250. for (; start != end; start++)
  251. original.parent().insert_copy_before(*start, original.node());
  252. }
  253. else if (strcmp(pos.value(), "after") == 0)
  254. {
  255. pugi::xml_node::iterator start = patch.begin();
  256. pugi::xml_node::iterator end = patch.end();
  257. // There can not be two consecutive text nodes, so check to see if they need to be combined
  258. // If they have been we can skip the first node of the nodes to add
  259. if (CombineText(patch.first_child(), original.node(), false))
  260. start++;
  261. // There can not be two consecutive text nodes, so check to see if they need to be combined
  262. // If they have been we can skip the last node of the nodes to add
  263. if (CombineText(patch.last_child(), original.node().next_sibling(), true))
  264. end--;
  265. pugi::xml_node pos = original.node();
  266. for (; start != end; start++)
  267. pos = original.parent().insert_copy_after(*start, pos);
  268. }
  269. }
  270. void XMLFile::AddAttribute(const pugi::xml_node& patch, pugi::xpath_node& original)
  271. {
  272. pugi::xml_attribute attribute = patch.attribute("type");
  273. if (!patch.first_child() && patch.first_child().type() != pugi::node_pcdata)
  274. {
  275. LOGERRORF("XML Patch failed calling Add due to attempting to add non text to an attribute for %s.", attribute.value());
  276. return;
  277. }
  278. String name(attribute.value());
  279. name = name.Substring(1);
  280. pugi::xml_attribute newAttribute = original.node().append_attribute(name.CString());
  281. newAttribute.set_value(patch.child_value());
  282. }
  283. bool XMLFile::CombineText(const pugi::xml_node& patch, pugi::xml_node original, bool prepend)
  284. {
  285. if (!patch || !original)
  286. return false;
  287. if ((patch.type() == pugi::node_pcdata && original.type() == pugi::node_pcdata) ||
  288. (patch.type() == pugi::node_cdata && original.type() == pugi::node_cdata))
  289. {
  290. if (prepend)
  291. original.set_value(ToString("%s%s", patch.value(), original.value()).CString());
  292. else
  293. original.set_value(ToString("%s%s", original.value(), patch.value()).CString());
  294. return true;
  295. }
  296. return false;
  297. }
  298. }