XMLFile.cpp 12 KB

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