StyleSheetNode.cpp 12 KB

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