StyleSheetNode.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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::SetStructurallyVolatileRecursive(bool ancestor_is_structural_pseudo_class)
  151. {
  152. // If any ancestor or descendant is a structural pseudo class, then we are structurally volatile.
  153. bool self_is_structural_pseudo_class = (!structural_selectors.empty());
  154. // Check our children for structural pseudo-classes.
  155. bool descendant_is_structural_pseudo_class = false;
  156. for (auto& child : children)
  157. {
  158. if (child->SetStructurallyVolatileRecursive(self_is_structural_pseudo_class || ancestor_is_structural_pseudo_class))
  159. descendant_is_structural_pseudo_class = true;
  160. }
  161. is_structurally_volatile = (self_is_structural_pseudo_class || ancestor_is_structural_pseudo_class || descendant_is_structural_pseudo_class);
  162. return (self_is_structural_pseudo_class || descendant_is_structural_pseudo_class);
  163. }
  164. bool StyleSheetNode::EqualRequirements(const String& _tag, const String& _id, const StringList& _class_names, const StringList& _pseudo_class_names,
  165. const StructuralSelectorList& _structural_selectors, SelectorCombinator _combinator) const
  166. {
  167. if (tag != _tag)
  168. return false;
  169. if (id != _id)
  170. return false;
  171. if (class_names != _class_names)
  172. return false;
  173. if (pseudo_class_names != _pseudo_class_names)
  174. return false;
  175. if (structural_selectors != _structural_selectors)
  176. return false;
  177. if (combinator != _combinator)
  178. return false;
  179. return true;
  180. }
  181. // Returns the specificity of this node.
  182. int StyleSheetNode::GetSpecificity() const
  183. {
  184. return specificity;
  185. }
  186. // Imports properties from a single rule definition (ie, with a shared specificity) into the node's
  187. // properties.
  188. void StyleSheetNode::ImportProperties(const PropertyDictionary& _properties, int rule_specificity)
  189. {
  190. properties.Import(_properties, specificity + rule_specificity);
  191. }
  192. // Returns the node's default properties.
  193. const PropertyDictionary& StyleSheetNode::GetProperties() const
  194. {
  195. return properties;
  196. }
  197. bool StyleSheetNode::Match(const Element* element) const
  198. {
  199. if (!tag.empty() && tag != element->GetTagName())
  200. return false;
  201. if (!id.empty() && id != element->GetId())
  202. return false;
  203. if (!MatchClassPseudoClass(element))
  204. return false;
  205. if (!MatchStructuralSelector(element))
  206. return false;
  207. return true;
  208. }
  209. inline bool StyleSheetNode::MatchClassPseudoClass(const Element* element) const
  210. {
  211. for (auto& name : class_names)
  212. {
  213. if (!element->IsClassSet(name))
  214. return false;
  215. }
  216. for (auto& name : pseudo_class_names)
  217. {
  218. if (!element->IsPseudoClassSet(name))
  219. return false;
  220. }
  221. return true;
  222. }
  223. inline bool StyleSheetNode::MatchStructuralSelector(const Element* element) const
  224. {
  225. for (auto& node_selector : structural_selectors)
  226. {
  227. if (!IsSelectorApplicable(element, node_selector))
  228. return false;
  229. }
  230. return true;
  231. }
  232. bool StyleSheetNode::IsApplicable(const Element* const in_element) const
  233. {
  234. // Determine whether the element matches the current node and its entire lineage. The entire hierarchy of the element's document will be
  235. // considered during the match as necessary.
  236. // 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
  237. // particular order for performance reasons .
  238. for (const String& name : pseudo_class_names)
  239. {
  240. if (!in_element->IsPseudoClassSet(name))
  241. return false;
  242. }
  243. if (!tag.empty() && tag != in_element->GetTagName())
  244. return false;
  245. for (const String& name : class_names)
  246. {
  247. if (!in_element->IsClassSet(name))
  248. return false;
  249. }
  250. if (!id.empty() && id != in_element->GetId())
  251. return false;
  252. const Element* element = in_element;
  253. // Walk up through all our parent nodes, each one of them must be matched by some ancestor or sibling element.
  254. for (const StyleSheetNode* node = parent; node && node->parent; node = node->parent)
  255. {
  256. switch (node->combinator)
  257. {
  258. case SelectorCombinator::None:
  259. case SelectorCombinator::Child:
  260. {
  261. // Try a match on every element ancestor. If it succeeds, we continue on to the next node.
  262. for (element = element->GetParentNode(); element; element = element->GetParentNode())
  263. {
  264. if (node->Match(element))
  265. break;
  266. // If the node has a child combinator we must match this first ancestor.
  267. else if (node->combinator == SelectorCombinator::Child)
  268. return false;
  269. }
  270. }
  271. break;
  272. case SelectorCombinator::NextSibling:
  273. case SelectorCombinator::SubsequentSibling:
  274. {
  275. // Try a match on every element ancestor. If it succeeds, we continue on to the next node.
  276. for (element = element->GetPreviousSibling(); element; element = element->GetPreviousSibling())
  277. {
  278. if (node->Match(element) && !IsTextElement(in_element))
  279. break;
  280. // If the node has a next-sibling combinator we must match this first sibling.
  281. else if (node->combinator == SelectorCombinator::NextSibling && !IsTextElement(in_element))
  282. return false;
  283. }
  284. }
  285. break;
  286. }
  287. // We have run out of element ancestors before we matched every node. Bail out.
  288. if (!element)
  289. return false;
  290. }
  291. // Finally, check the structural selector requirements last as they can be quite slow.
  292. if (!MatchStructuralSelector(in_element))
  293. return false;
  294. return true;
  295. }
  296. bool StyleSheetNode::IsStructurallyVolatile() const
  297. {
  298. return is_structurally_volatile;
  299. }
  300. void StyleSheetNode::CalculateAndSetSpecificity()
  301. {
  302. // First calculate the specificity of this node alone.
  303. specificity = 0;
  304. if (!tag.empty())
  305. specificity += SelectorSpecificity::Tag;
  306. if (!id.empty())
  307. specificity += SelectorSpecificity::ID;
  308. specificity += SelectorSpecificity::Class * (int)class_names.size();
  309. specificity += SelectorSpecificity::PseudoClass * (int)pseudo_class_names.size();
  310. for (const StructuralSelector& selector : structural_selectors)
  311. specificity += selector.specificity;
  312. // Then add our parent's specificity onto ours.
  313. if (parent)
  314. specificity += parent->specificity;
  315. }
  316. } // namespace Rml