StyleSheetNode.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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-2023 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. #include <tuple>
  36. namespace Rml {
  37. static inline bool IsTextElement(const Element* element)
  38. {
  39. return element->GetTagName() == "#text";
  40. }
  41. StyleSheetNode::StyleSheetNode()
  42. {
  43. CalculateAndSetSpecificity();
  44. }
  45. StyleSheetNode::StyleSheetNode(StyleSheetNode* parent, const CompoundSelector& selector) : parent(parent), selector(selector)
  46. {
  47. CalculateAndSetSpecificity();
  48. }
  49. StyleSheetNode::StyleSheetNode(StyleSheetNode* parent, CompoundSelector&& selector) : parent(parent), selector(std::move(selector))
  50. {
  51. CalculateAndSetSpecificity();
  52. }
  53. StyleSheetNode* StyleSheetNode::GetOrCreateChildNode(const CompoundSelector& other)
  54. {
  55. // See if we match an existing child
  56. for (const auto& child : children)
  57. {
  58. if (child->selector == other)
  59. return child.get();
  60. }
  61. // We don't, so create a new child
  62. auto child = MakeUnique<StyleSheetNode>(this, other);
  63. StyleSheetNode* result = child.get();
  64. children.push_back(std::move(child));
  65. return result;
  66. }
  67. StyleSheetNode* StyleSheetNode::GetOrCreateChildNode(CompoundSelector&& other)
  68. {
  69. // See if we match an existing child
  70. for (const auto& child : children)
  71. {
  72. if (child->selector == other)
  73. return child.get();
  74. }
  75. // We don't, so create a new child
  76. auto child = MakeUnique<StyleSheetNode>(this, std::move(other));
  77. StyleSheetNode* result = child.get();
  78. children.push_back(std::move(child));
  79. return result;
  80. }
  81. void StyleSheetNode::MergeHierarchy(StyleSheetNode* node, int specificity_offset)
  82. {
  83. RMLUI_ZoneScoped;
  84. // Merge the other node's properties into ours.
  85. properties.Merge(node->properties, specificity_offset);
  86. for (const auto& other_child : node->children)
  87. {
  88. StyleSheetNode* local_node = GetOrCreateChildNode(other_child->selector);
  89. local_node->MergeHierarchy(other_child.get(), specificity_offset);
  90. }
  91. }
  92. UniquePtr<StyleSheetNode> StyleSheetNode::DeepCopy(StyleSheetNode* in_parent) const
  93. {
  94. RMLUI_ZoneScoped;
  95. auto node = MakeUnique<StyleSheetNode>(in_parent, selector);
  96. node->properties = properties;
  97. node->children.resize(children.size());
  98. for (size_t i = 0; i < children.size(); i++)
  99. {
  100. node->children[i] = children[i]->DeepCopy(node.get());
  101. }
  102. return node;
  103. }
  104. void StyleSheetNode::BuildIndex(StyleSheetIndex& styled_node_index) const
  105. {
  106. // If this has properties defined, then we insert it into the styled node index.
  107. if (properties.GetNumProperties() > 0)
  108. {
  109. auto IndexInsertNode = [](StyleSheetIndex::NodeIndex& node_index, const String& key, const StyleSheetNode* node) {
  110. StyleSheetIndex::NodeList& nodes = node_index[Hash<String>()(key)];
  111. auto it = std::find(nodes.begin(), nodes.end(), node);
  112. if (it == nodes.end())
  113. nodes.push_back(node);
  114. };
  115. // Add this node to the appropriate index for looking up applicable nodes later. Prioritize the most unique requirement first and the most
  116. // general requirement last. This way we are able to rule out as many nodes as possible as quickly as possible.
  117. if (!selector.id.empty())
  118. {
  119. IndexInsertNode(styled_node_index.ids, selector.id, this);
  120. }
  121. else if (!selector.class_names.empty())
  122. {
  123. // @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
  124. // class with the most unique name. For example by adding the class from this node's list that has the fewest existing matches.
  125. IndexInsertNode(styled_node_index.classes, selector.class_names.front(), this);
  126. }
  127. else if (!selector.tag.empty())
  128. {
  129. IndexInsertNode(styled_node_index.tags, selector.tag, this);
  130. }
  131. else
  132. {
  133. styled_node_index.other.push_back(this);
  134. }
  135. }
  136. for (auto& child : children)
  137. child->BuildIndex(styled_node_index);
  138. }
  139. int StyleSheetNode::GetSpecificity() const
  140. {
  141. return specificity;
  142. }
  143. void StyleSheetNode::ImportProperties(const PropertyDictionary& _properties, int rule_specificity)
  144. {
  145. properties.Import(_properties, specificity + rule_specificity);
  146. }
  147. const PropertyDictionary& StyleSheetNode::GetProperties() const
  148. {
  149. return properties;
  150. }
  151. bool StyleSheetNode::Match(const Element* element, const Element* scope) const
  152. {
  153. if (!selector.tag.empty() && selector.tag != element->GetTagName())
  154. return false;
  155. if (!selector.id.empty() && selector.id != element->GetId())
  156. return false;
  157. for (auto& name : selector.class_names)
  158. {
  159. if (!element->IsClassSet(name))
  160. return false;
  161. }
  162. for (auto& name : selector.pseudo_class_names)
  163. {
  164. if (!element->IsPseudoClassSet(name))
  165. return false;
  166. }
  167. if (!selector.attributes.empty() && !MatchAttributes(element))
  168. return false;
  169. if (!selector.structural_selectors.empty() && !MatchStructuralSelector(element, scope))
  170. return false;
  171. return true;
  172. }
  173. bool StyleSheetNode::MatchStructuralSelector(const Element* element, const Element* scope) const
  174. {
  175. for (auto& node_selector : selector.structural_selectors)
  176. {
  177. if (!IsSelectorApplicable(element, node_selector, scope))
  178. return false;
  179. }
  180. return true;
  181. }
  182. bool StyleSheetNode::MatchAttributes(const Element* element) const
  183. {
  184. for (const AttributeSelector& attribute : selector.attributes)
  185. {
  186. const Variant* variant = element->GetAttribute(attribute.name);
  187. if (!variant)
  188. return false;
  189. if (attribute.type == AttributeSelectorType::Always)
  190. continue;
  191. String buffer;
  192. const String* element_value_ptr = &buffer;
  193. if (variant->GetType() == Variant::STRING)
  194. element_value_ptr = &variant->GetReference<String>();
  195. else
  196. variant->GetInto(buffer);
  197. const String& element_value = *element_value_ptr;
  198. const String& css_value = attribute.value;
  199. auto BeginsWith = [](const String& target, const String& prefix) {
  200. return prefix.size() <= target.size() && std::equal(prefix.begin(), prefix.end(), target.begin());
  201. };
  202. auto EndsWith = [](const String& target, const String& suffix) {
  203. return suffix.size() <= target.size() && std::equal(suffix.rbegin(), suffix.rend(), target.rbegin());
  204. };
  205. switch (attribute.type)
  206. {
  207. case AttributeSelectorType::Always: break;
  208. case AttributeSelectorType::Equal:
  209. if (element_value != css_value)
  210. return false;
  211. break;
  212. case AttributeSelectorType::InList:
  213. {
  214. bool found = false;
  215. for (size_t index = element_value.find(css_value); index != String::npos; index = element_value.find(css_value, index + 1))
  216. {
  217. const size_t index_right = index + css_value.size();
  218. const bool whitespace_left = (index == 0 || element_value[index - 1] == ' ');
  219. const bool whitespace_right = (index_right == element_value.size() || element_value[index_right] == ' ');
  220. if (whitespace_left && whitespace_right)
  221. {
  222. found = true;
  223. break;
  224. }
  225. }
  226. if (!found)
  227. return false;
  228. }
  229. break;
  230. case AttributeSelectorType::BeginsWithThenHyphen:
  231. // Begins with 'css_value' followed by a hyphen, or matches exactly.
  232. if (!BeginsWith(element_value, css_value) || (element_value.size() != css_value.size() && element_value[css_value.size()] != '-'))
  233. return false;
  234. break;
  235. case AttributeSelectorType::BeginsWith:
  236. if (!BeginsWith(element_value, css_value))
  237. return false;
  238. break;
  239. case AttributeSelectorType::EndsWith:
  240. if (!EndsWith(element_value, css_value))
  241. return false;
  242. break;
  243. case AttributeSelectorType::Contains:
  244. if (element_value.find(css_value) == String::npos)
  245. return false;
  246. break;
  247. }
  248. }
  249. return true;
  250. }
  251. bool StyleSheetNode::TraverseMatch(const Element* element, const Element* scope) const
  252. {
  253. RMLUI_ASSERT(parent);
  254. if (!parent->parent)
  255. return true;
  256. switch (selector.combinator)
  257. {
  258. case SelectorCombinator::Descendant:
  259. case SelectorCombinator::Child:
  260. {
  261. // 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
  262. // hierarchy using the next element parent. Repeat until we run out of elements.
  263. for (element = element->GetParentNode(); element; element = element->GetParentNode())
  264. {
  265. if (parent->Match(element, scope) && parent->TraverseMatch(element, scope))
  266. return true;
  267. // If the node has a child combinator we must match this first ancestor.
  268. else if (selector.combinator == SelectorCombinator::Child)
  269. return false;
  270. }
  271. }
  272. break;
  273. case SelectorCombinator::NextSibling:
  274. case SelectorCombinator::SubsequentSibling:
  275. {
  276. Element* parent_element = element->GetParentNode();
  277. if (!parent_element)
  278. return false;
  279. const int preceding_sibling_index = [element, parent_element] {
  280. const int num_children = parent_element->GetNumChildren(true);
  281. for (int i = 0; i < num_children; i++)
  282. {
  283. if (parent_element->GetChild(i) == element)
  284. return i - 1;
  285. }
  286. return -1;
  287. }();
  288. // 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.
  289. for (int i = preceding_sibling_index; i >= 0; i--)
  290. {
  291. element = parent_element->GetChild(i);
  292. // 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
  293. // text elements don't have children and thus any ancestor is not a text element.
  294. if (IsTextElement(element))
  295. continue;
  296. else if (parent->Match(element, scope) && parent->TraverseMatch(element, scope))
  297. return true;
  298. // If the node has a next-sibling combinator we must match this first sibling.
  299. else if (selector.combinator == SelectorCombinator::NextSibling)
  300. return false;
  301. }
  302. }
  303. break;
  304. }
  305. // We have run out of element ancestors before we matched every node. Bail out.
  306. return false;
  307. }
  308. bool StyleSheetNode::IsApplicable(const Element* element, const Element* scope) const
  309. {
  310. // Determine whether the element matches the current node and its entire lineage. The entire hierarchy of the element's document will be
  311. // considered during the match as necessary.
  312. // 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
  313. // particular order for performance reasons.
  314. for (const String& name : selector.pseudo_class_names)
  315. {
  316. if (!element->IsPseudoClassSet(name))
  317. return false;
  318. }
  319. if (!selector.tag.empty() && selector.tag != element->GetTagName())
  320. return false;
  321. for (const String& name : selector.class_names)
  322. {
  323. if (!element->IsClassSet(name))
  324. return false;
  325. }
  326. if (!selector.id.empty() && selector.id != element->GetId())
  327. return false;
  328. if (!selector.attributes.empty() && !MatchAttributes(element))
  329. return false;
  330. // Check the structural selector requirements last as they can be quite slow.
  331. if (!selector.structural_selectors.empty() && !MatchStructuralSelector(element, scope))
  332. return false;
  333. // Walk up through all our parent nodes, each one of them must be matched by some ancestor or sibling element.
  334. if (parent && !TraverseMatch(element, scope))
  335. return false;
  336. return true;
  337. }
  338. void StyleSheetNode::CalculateAndSetSpecificity()
  339. {
  340. // First calculate the specificity of this node alone.
  341. specificity = 0;
  342. if (!selector.tag.empty())
  343. specificity += SelectorSpecificity::Tag;
  344. if (!selector.id.empty())
  345. specificity += SelectorSpecificity::ID;
  346. specificity += SelectorSpecificity::Class * (int)selector.class_names.size();
  347. specificity += SelectorSpecificity::Attribute * (int)selector.attributes.size();
  348. specificity += SelectorSpecificity::PseudoClass * (int)selector.pseudo_class_names.size();
  349. for (const StructuralSelector& selector : selector.structural_selectors)
  350. specificity += selector.specificity;
  351. // Then add our parent's specificity onto ours.
  352. if (parent)
  353. specificity += parent->specificity;
  354. }
  355. } // namespace Rml