StyleSheetNode.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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 "StyleSheetNodeSelector.h"
  34. #include <algorithm>
  35. namespace Rml {
  36. StyleSheetNode::StyleSheetNode()
  37. {
  38. CalculateAndSetSpecificity();
  39. }
  40. StyleSheetNode::StyleSheetNode(StyleSheetNode* parent, const String& tag, const String& id, const StringList& classes,
  41. const StringList& pseudo_classes, const StructuralSelectorList& structural_selectors, SelectorCombinator combinator) :
  42. parent(parent),
  43. tag(tag), id(id), class_names(classes), pseudo_class_names(pseudo_classes), structural_selectors(structural_selectors), combinator(combinator)
  44. {
  45. CalculateAndSetSpecificity();
  46. }
  47. StyleSheetNode::StyleSheetNode(StyleSheetNode* parent, String&& tag, String&& id, StringList&& classes, StringList&& pseudo_classes,
  48. StructuralSelectorList&& structural_selectors, SelectorCombinator combinator) :
  49. parent(parent),
  50. tag(std::move(tag)), id(std::move(id)), class_names(std::move(classes)), pseudo_class_names(std::move(pseudo_classes)),
  51. structural_selectors(std::move(structural_selectors)), combinator(combinator)
  52. {
  53. CalculateAndSetSpecificity();
  54. }
  55. StyleSheetNode* StyleSheetNode::GetOrCreateChildNode(const StyleSheetNode& other)
  56. {
  57. // See if we match the target child
  58. for (const auto& child : children)
  59. {
  60. if (child->EqualRequirements(other.tag, other.id, other.class_names, other.pseudo_class_names, other.structural_selectors, other.combinator))
  61. return child.get();
  62. }
  63. // We don't, so create a new child
  64. auto child = MakeUnique<StyleSheetNode>(this, other.tag, other.id, other.class_names, other.pseudo_class_names, other.structural_selectors,
  65. other.combinator);
  66. StyleSheetNode* result = child.get();
  67. children.push_back(std::move(child));
  68. return result;
  69. }
  70. StyleSheetNode* StyleSheetNode::GetOrCreateChildNode(String&& tag, String&& id, StringList&& classes, StringList&& pseudo_classes,
  71. StructuralSelectorList&& structural_pseudo_classes, SelectorCombinator combinator)
  72. {
  73. // See if we match an existing child
  74. for (const auto& child : children)
  75. {
  76. if (child->EqualRequirements(tag, id, classes, pseudo_classes, structural_pseudo_classes, combinator))
  77. return child.get();
  78. }
  79. // We don't, so create a new child
  80. auto child = MakeUnique<StyleSheetNode>(this, std::move(tag), std::move(id), std::move(classes), std::move(pseudo_classes),
  81. std::move(structural_pseudo_classes), combinator);
  82. StyleSheetNode* result = child.get();
  83. children.push_back(std::move(child));
  84. return result;
  85. }
  86. // Merges an entire tree hierarchy into our hierarchy.
  87. void StyleSheetNode::MergeHierarchy(StyleSheetNode* node, int specificity_offset)
  88. {
  89. RMLUI_ZoneScoped;
  90. // Merge the other node's properties into ours.
  91. properties.Merge(node->properties, specificity_offset);
  92. for (const auto& other_child : node->children)
  93. {
  94. StyleSheetNode* local_node = GetOrCreateChildNode(*other_child);
  95. local_node->MergeHierarchy(other_child.get(), specificity_offset);
  96. }
  97. }
  98. UniquePtr<StyleSheetNode> StyleSheetNode::DeepCopy(StyleSheetNode* in_parent) const
  99. {
  100. RMLUI_ZoneScoped;
  101. auto node = MakeUnique<StyleSheetNode>(in_parent, tag, id, class_names, pseudo_class_names, structural_selectors, combinator);
  102. node->properties = properties;
  103. node->children.resize(children.size());
  104. for (size_t i = 0; i < children.size(); i++)
  105. {
  106. node->children[i] = children[i]->DeepCopy(node.get());
  107. }
  108. return node;
  109. }
  110. // Builds up a style sheet's index recursively.
  111. void StyleSheetNode::BuildIndex(StyleSheetIndex& styled_node_index) const
  112. {
  113. // If this has properties defined, then we insert it into the styled node index.
  114. if (properties.GetNumProperties() > 0)
  115. {
  116. auto IndexInsertNode = [](StyleSheetIndex::NodeIndex& node_index, const String& key, const StyleSheetNode* node) {
  117. StyleSheetIndex::NodeList& nodes = node_index[Hash<String>()(key)];
  118. auto it = std::find(nodes.begin(), nodes.end(), node);
  119. if (it == nodes.end())
  120. nodes.push_back(node);
  121. };
  122. // Add this node to the appropriate index for looking up applicable nodes later. Prioritize the most unique requirement first and the most
  123. // general requirement last. This way we are able to rule out as many nodes as possible as quickly as possible.
  124. if (!id.empty())
  125. {
  126. IndexInsertNode(styled_node_index.ids, id, this);
  127. }
  128. else if (!class_names.empty())
  129. {
  130. // @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
  131. // class with the most unique name. For example by adding the class from this node's list that has the fewest existing matches.
  132. IndexInsertNode(styled_node_index.classes, class_names.front(), this);
  133. }
  134. else if (!tag.empty())
  135. {
  136. IndexInsertNode(styled_node_index.tags, tag, this);
  137. }
  138. else
  139. {
  140. styled_node_index.other.push_back(this);
  141. }
  142. }
  143. for (auto& child : children)
  144. child->BuildIndex(styled_node_index);
  145. }
  146. bool StyleSheetNode::SetStructurallyVolatileRecursive(bool ancestor_is_structural_pseudo_class)
  147. {
  148. // If any ancestor or descendant is a structural pseudo class, then we are structurally volatile.
  149. bool self_is_structural_pseudo_class = (!structural_selectors.empty());
  150. // Check our children for structural pseudo-classes.
  151. bool descendant_is_structural_pseudo_class = false;
  152. for (auto& child : children)
  153. {
  154. if (child->SetStructurallyVolatileRecursive(self_is_structural_pseudo_class || ancestor_is_structural_pseudo_class))
  155. descendant_is_structural_pseudo_class = true;
  156. }
  157. is_structurally_volatile = (self_is_structural_pseudo_class || ancestor_is_structural_pseudo_class || descendant_is_structural_pseudo_class);
  158. return (self_is_structural_pseudo_class || descendant_is_structural_pseudo_class);
  159. }
  160. bool StyleSheetNode::EqualRequirements(const String& _tag, const String& _id, const StringList& _class_names, const StringList& _pseudo_class_names,
  161. const StructuralSelectorList& _structural_selectors, SelectorCombinator _combinator) const
  162. {
  163. if (tag != _tag)
  164. return false;
  165. if (id != _id)
  166. return false;
  167. if (class_names != _class_names)
  168. return false;
  169. if (pseudo_class_names != _pseudo_class_names)
  170. return false;
  171. if (structural_selectors != _structural_selectors)
  172. return false;
  173. if (combinator != _combinator)
  174. return false;
  175. return true;
  176. }
  177. // Returns the specificity of this node.
  178. int StyleSheetNode::GetSpecificity() const
  179. {
  180. return specificity;
  181. }
  182. // Imports properties from a single rule definition (ie, with a shared specificity) into the node's
  183. // properties.
  184. void StyleSheetNode::ImportProperties(const PropertyDictionary& _properties, int rule_specificity)
  185. {
  186. properties.Import(_properties, specificity + rule_specificity);
  187. }
  188. // Returns the node's default properties.
  189. const PropertyDictionary& StyleSheetNode::GetProperties() const
  190. {
  191. return properties;
  192. }
  193. inline bool StyleSheetNode::Match(const Element* element) const
  194. {
  195. if (!tag.empty() && tag != element->GetTagName())
  196. return false;
  197. if (!id.empty() && id != element->GetId())
  198. return false;
  199. if (!MatchClassPseudoClass(element))
  200. return false;
  201. if (!MatchStructuralSelector(element))
  202. return false;
  203. return true;
  204. }
  205. inline bool StyleSheetNode::MatchClassPseudoClass(const Element* element) const
  206. {
  207. for (auto& name : class_names)
  208. {
  209. if (!element->IsClassSet(name))
  210. return false;
  211. }
  212. for (auto& name : pseudo_class_names)
  213. {
  214. if (!element->IsPseudoClassSet(name))
  215. return false;
  216. }
  217. return true;
  218. }
  219. inline bool StyleSheetNode::MatchStructuralSelector(const Element* element) const
  220. {
  221. for (auto& node_selector : structural_selectors)
  222. {
  223. if (!node_selector.selector->IsApplicable(element, node_selector.a, node_selector.b))
  224. return false;
  225. }
  226. return true;
  227. }
  228. // Returns true if this node is applicable to the given element, given its IDs, classes and heritage.
  229. bool StyleSheetNode::IsApplicable(const Element* const in_element) const
  230. {
  231. // Determine whether the element matches the current node and its entire lineage. The entire hierarchy of
  232. // the element's document will be considered during the match as necessary.
  233. for (const String& name : pseudo_class_names)
  234. {
  235. if (!in_element->IsPseudoClassSet(name))
  236. return false;
  237. }
  238. if (!tag.empty() && tag != in_element->GetTagName())
  239. return false;
  240. for (const String& name : class_names)
  241. {
  242. if (!in_element->IsClassSet(name))
  243. return false;
  244. }
  245. if (!id.empty() && id != in_element->GetId())
  246. return false;
  247. const Element* element = in_element;
  248. // Walk up through all our parent nodes, each one of them must be matched by some ancestor or sibling element.
  249. for (const StyleSheetNode* node = parent; node && node->parent; node = node->parent)
  250. {
  251. switch (node->combinator)
  252. {
  253. case SelectorCombinator::None:
  254. case SelectorCombinator::Child:
  255. {
  256. // Try a match on every element ancestor. If it succeeds, we continue on to the next node.
  257. for (element = element->GetParentNode(); element; element = element->GetParentNode())
  258. {
  259. if (node->Match(element))
  260. break;
  261. // If the node has a child combinator we must match this first ancestor.
  262. else if (node->combinator == SelectorCombinator::Child)
  263. return false;
  264. }
  265. }
  266. break;
  267. case SelectorCombinator::NextSibling:
  268. case SelectorCombinator::SubsequentSibling:
  269. {
  270. // Try a match on every element ancestor. If it succeeds, we continue on to the next node.
  271. for (element = element->GetPreviousSibling(); element; element = element->GetPreviousSibling())
  272. {
  273. if (node->Match(element))
  274. break;
  275. // If the node has a next-sibling combinator we must match this first sibling.
  276. else if (node->combinator == SelectorCombinator::NextSibling)
  277. return false;
  278. }
  279. }
  280. break;
  281. }
  282. // We have run out of element ancestors before we matched every node. Bail out.
  283. if (!element)
  284. return false;
  285. }
  286. // Finally, check the structural selector requirements last as they can be quite slow.
  287. if (!MatchStructuralSelector(in_element))
  288. return false;
  289. return true;
  290. }
  291. bool StyleSheetNode::IsStructurallyVolatile() const
  292. {
  293. return is_structurally_volatile;
  294. }
  295. void StyleSheetNode::CalculateAndSetSpecificity()
  296. {
  297. // Calculate the specificity of just this node; tags are worth 10,000, IDs 1,000,000 and other specifiers (classes
  298. // and pseudo-classes) 100,000.
  299. specificity = 0;
  300. if (!tag.empty())
  301. specificity += 10'000;
  302. if (!id.empty())
  303. specificity += 1'000'000;
  304. specificity += 100'000 * (int)class_names.size();
  305. specificity += 100'000 * (int)pseudo_class_names.size();
  306. specificity += 100'000 * (int)structural_selectors.size();
  307. // Add our parent's specificity onto ours.
  308. if (parent)
  309. specificity += parent->specificity;
  310. }
  311. } // namespace Rml