StyleSheetNode.cpp 13 KB

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