XMLFile.cpp 12 KB

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