XMLFile.cpp 13 KB

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