StyleSheetNode.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. /*
  2. * This source file is part of RmlUi, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://github.com/mikke89/RmlUi
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. * Copyright (c) 2019 The RmlUi Team, and contributors
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. */
  28. #include "StyleSheetNode.h"
  29. #include "../../Include/RmlUi/Core/Element.h"
  30. #include "../../Include/RmlUi/Core/Profiling.h"
  31. #include "../../Include/RmlUi/Core/StyleSheet.h"
  32. #include "StyleSheetFactory.h"
  33. #include "StyleSheetSelector.h"
  34. #include <algorithm>
  35. namespace Rml {
  36. static inline bool IsTextElement(const Element* element)
  37. {
  38. return element->GetTagName() == "#text";
  39. }
  40. StyleSheetNode::StyleSheetNode()
  41. {
  42. CalculateAndSetSpecificity();
  43. }
  44. StyleSheetNode::StyleSheetNode(StyleSheetNode* parent, const String& tag, const String& id, const StringList& classes,
  45. const StringList& pseudo_classes, const StructuralSelectorList& structural_selectors, SelectorCombinator combinator) :
  46. parent(parent),
  47. tag(tag), id(id), class_names(classes), pseudo_class_names(pseudo_classes), structural_selectors(structural_selectors), combinator(combinator)
  48. {
  49. CalculateAndSetSpecificity();
  50. }
  51. StyleSheetNode::StyleSheetNode(StyleSheetNode* parent, String&& tag, String&& id, StringList&& classes, StringList&& pseudo_classes,
  52. StructuralSelectorList&& structural_selectors, SelectorCombinator combinator) :
  53. parent(parent),
  54. tag(std::move(tag)), id(std::move(id)), class_names(std::move(classes)), pseudo_class_names(std::move(pseudo_classes)),
  55. structural_selectors(std::move(structural_selectors)), combinator(combinator)
  56. {
  57. CalculateAndSetSpecificity();
  58. }
  59. StyleSheetNode* StyleSheetNode::GetOrCreateChildNode(const StyleSheetNode& other)
  60. {
  61. // See if we match the target child
  62. for (const auto& child : children)
  63. {
  64. if (child->EqualRequirements(other.tag, other.id, other.class_names, other.pseudo_class_names, other.structural_selectors, other.combinator))
  65. return child.get();
  66. }
  67. // We don't, so create a new child
  68. auto child = MakeUnique<StyleSheetNode>(this, other.tag, other.id, other.class_names, other.pseudo_class_names, other.structural_selectors,
  69. other.combinator);
  70. StyleSheetNode* result = child.get();
  71. children.push_back(std::move(child));
  72. return result;
  73. }
  74. StyleSheetNode* StyleSheetNode::GetOrCreateChildNode(String&& tag, String&& id, StringList&& classes, StringList&& pseudo_classes,
  75. StructuralSelectorList&& structural_pseudo_classes, SelectorCombinator combinator)
  76. {
  77. // See if we match an existing child
  78. for (const auto& child : children)
  79. {
  80. if (child->EqualRequirements(tag, id, classes, pseudo_classes, structural_pseudo_classes, combinator))
  81. return child.get();
  82. }
  83. // We don't, so create a new child
  84. auto child = MakeUnique<StyleSheetNode>(this, std::move(tag), std::move(id), std::move(classes), std::move(pseudo_classes),
  85. std::move(structural_pseudo_classes), combinator);
  86. StyleSheetNode* result = child.get();
  87. children.push_back(std::move(child));
  88. return result;
  89. }
  90. // Merges an entire tree hierarchy into our hierarchy.
  91. void StyleSheetNode::MergeHierarchy(StyleSheetNode* node, int specificity_offset)
  92. {
  93. RMLUI_ZoneScoped;
  94. // Merge the other node's properties into ours.
  95. properties.Merge(node->properties, specificity_offset);
  96. for (const auto& other_child : node->children)
  97. {
  98. StyleSheetNode* local_node = GetOrCreateChildNode(*other_child);
  99. local_node->MergeHierarchy(other_child.get(), specificity_offset);
  100. }
  101. }
  102. UniquePtr<StyleSheetNode> StyleSheetNode::DeepCopy(StyleSheetNode* in_parent) const
  103. {
  104. RMLUI_ZoneScoped;
  105. auto node = MakeUnique<StyleSheetNode>(in_parent, tag, id, class_names, pseudo_class_names, structural_selectors, combinator);
  106. node->properties = properties;
  107. node->children.resize(children.size());
  108. for (size_t i = 0; i < children.size(); i++)
  109. {
  110. node->children[i] = children[i]->DeepCopy(node.get());
  111. }
  112. return node;
  113. }
  114. // Builds up a style sheet's index recursively.
  115. void StyleSheetNode::BuildIndex(StyleSheetIndex& styled_node_index) const
  116. {
  117. // If this has properties defined, then we insert it into the styled node index.
  118. if (properties.GetNumProperties() > 0)
  119. {
  120. auto IndexInsertNode = [](StyleSheetIndex::NodeIndex& node_index, const String& key, const StyleSheetNode* node) {
  121. StyleSheetIndex::NodeList& nodes = node_index[Hash<String>()(key)];
  122. auto it = std::find(nodes.begin(), nodes.end(), node);
  123. if (it == nodes.end())
  124. nodes.push_back(node);
  125. };
  126. // Add this node to the appropriate index for looking up applicable nodes later. Prioritize the most unique requirement first and the most
  127. // general requirement last. This way we are able to rule out as many nodes as possible as quickly as possible.
  128. if (!id.empty())
  129. {
  130. IndexInsertNode(styled_node_index.ids, id, this);
  131. }
  132. else if (!class_names.empty())
  133. {
  134. // @performance Right now we just use the first class for simplicity. Later we may want to devise a better strategy to try to add the
  135. // class with the most unique name. For example by adding the class from this node's list that has the fewest existing matches.
  136. IndexInsertNode(styled_node_index.classes, class_names.front(), this);
  137. }
  138. else if (!tag.empty())
  139. {
  140. IndexInsertNode(styled_node_index.tags, tag, this);
  141. }
  142. else
  143. {
  144. styled_node_index.other.push_back(this);
  145. }
  146. }
  147. for (auto& child : children)
  148. child->BuildIndex(styled_node_index);
  149. }
  150. bool StyleSheetNode::EqualRequirements(const String& _tag, const String& _id, const StringList& _class_names, const StringList& _pseudo_class_names,
  151. const StructuralSelectorList& _structural_selectors, SelectorCombinator _combinator) const
  152. {
  153. if (tag != _tag)
  154. return false;
  155. if (id != _id)
  156. return false;
  157. if (class_names != _class_names)
  158. return false;
  159. if (pseudo_class_names != _pseudo_class_names)
  160. return false;
  161. if (structural_selectors != _structural_selectors)
  162. return false;
  163. if (combinator != _combinator)
  164. return false;
  165. return true;
  166. }
  167. // Returns the specificity of this node.
  168. int StyleSheetNode::GetSpecificity() const
  169. {
  170. return specificity;
  171. }
  172. // Imports properties from a single rule definition (ie, with a shared specificity) into the node's
  173. // properties.
  174. void StyleSheetNode::ImportProperties(const PropertyDictionary& _properties, int rule_specificity)
  175. {
  176. properties.Import(_properties, specificity + rule_specificity);
  177. }
  178. // Returns the node's default properties.
  179. const PropertyDictionary& StyleSheetNode::GetProperties() const
  180. {
  181. return properties;
  182. }
  183. bool StyleSheetNode::Match(const Element* element) const
  184. {
  185. if (!tag.empty() && tag != element->GetTagName())
  186. return false;
  187. if (!id.empty() && id != element->GetId())
  188. return false;
  189. if (!MatchClassPseudoClass(element))
  190. return false;
  191. if (!MatchStructuralSelector(element))
  192. return false;
  193. return true;
  194. }
  195. inline bool StyleSheetNode::MatchClassPseudoClass(const Element* element) const
  196. {
  197. for (auto& name : class_names)
  198. {
  199. if (!element->IsClassSet(name))
  200. return false;
  201. }
  202. for (auto& name : pseudo_class_names)
  203. {
  204. if (!element->IsPseudoClassSet(name))
  205. return false;
  206. }
  207. return true;
  208. }
  209. inline bool StyleSheetNode::MatchStructuralSelector(const Element* element) const
  210. {
  211. for (auto& node_selector : structural_selectors)
  212. {
  213. if (!IsSelectorApplicable(element, node_selector))
  214. return false;
  215. }
  216. return true;
  217. }
  218. bool StyleSheetNode::TraverseMatch(const StyleSheetNode* node, const Element* element)
  219. {
  220. if (!node || !node->parent)
  221. return true;
  222. switch (node->combinator)
  223. {
  224. case SelectorCombinator::None:
  225. case SelectorCombinator::Child:
  226. {
  227. // Try to match the next element parent. If it succeeds we continue on to the next node, otherwise we try an alternate path through the
  228. // hierarchy using the next element parent. Repeat until we run out of elements.
  229. for (element = element->GetParentNode(); element; element = element->GetParentNode())
  230. {
  231. if (node->Match(element) && TraverseMatch(node->parent, element))
  232. return true;
  233. // If the node has a child combinator we must match this first ancestor.
  234. else if (node->combinator == SelectorCombinator::Child)
  235. return false;
  236. }
  237. }
  238. break;
  239. case SelectorCombinator::NextSibling:
  240. case SelectorCombinator::SubsequentSibling:
  241. {
  242. // Try to match the previous sibling. If it succeeds we continue on to the next node, otherwise we try to again with its previous sibling.
  243. for (element = element->GetPreviousSibling(); element; element = element->GetPreviousSibling())
  244. {
  245. // First check if our sibling is a text element and if so skip it. For the descendant/child combinator above we can omit this step since
  246. // text elements don't have children and thus any ancestor is not a text element.
  247. if (IsTextElement(element))
  248. continue;
  249. else if (node->Match(element) && TraverseMatch(node->parent, element))
  250. return true;
  251. // If the node has a next-sibling combinator we must match this first sibling.
  252. else if (node->combinator == SelectorCombinator::NextSibling)
  253. return false;
  254. }
  255. }
  256. break;
  257. }
  258. // We have run out of element ancestors before we matched every node. Bail out.
  259. return false;
  260. }
  261. bool StyleSheetNode::IsApplicable(const Element* element) const
  262. {
  263. // Determine whether the element matches the current node and its entire lineage. The entire hierarchy of the element's document will be
  264. // considered during the match as necessary.
  265. // We could in principle just call Match() here and then go on with the ancestor style nodes. Instead, we test the requirements of this node in a
  266. // particular order for performance reasons.
  267. for (const String& name : pseudo_class_names)
  268. {
  269. if (!element->IsPseudoClassSet(name))
  270. return false;
  271. }
  272. if (!tag.empty() && tag != element->GetTagName())
  273. return false;
  274. for (const String& name : class_names)
  275. {
  276. if (!element->IsClassSet(name))
  277. return false;
  278. }
  279. if (!id.empty() && id != element->GetId())
  280. return false;
  281. // Walk up through all our parent nodes, each one of them must be matched by some ancestor or sibling element.
  282. if (!TraverseMatch(parent, element))
  283. return false;
  284. // Finally, check the structural selector requirements last as they can be quite slow.
  285. if (!MatchStructuralSelector(element))
  286. return false;
  287. return true;
  288. }
  289. void StyleSheetNode::CalculateAndSetSpecificity()
  290. {
  291. // First calculate the specificity of this node alone.
  292. specificity = 0;
  293. if (!tag.empty())
  294. specificity += SelectorSpecificity::Tag;
  295. if (!id.empty())
  296. specificity += SelectorSpecificity::ID;
  297. specificity += SelectorSpecificity::Class * (int)class_names.size();
  298. specificity += SelectorSpecificity::PseudoClass * (int)pseudo_class_names.size();
  299. for (const StructuralSelector& selector : structural_selectors)
  300. specificity += selector.specificity;
  301. // Then add our parent's specificity onto ours.
  302. if (parent)
  303. specificity += parent->specificity;
  304. }
  305. } // namespace Rml