StyleSheetNode.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. /*
  2. * This source file is part of libRocket, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://www.librocket.com
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. *
  26. */
  27. #include "precompiled.h"
  28. #include "StyleSheetNode.h"
  29. #include <algorithm>
  30. #include "../../Include/Rocket/Core/Element.h"
  31. #include "StyleSheetFactory.h"
  32. #include "StyleSheetNodeSelector.h"
  33. namespace Rocket {
  34. namespace Core {
  35. StyleSheetNode::StyleSheetNode(const String& name, NodeType _type, StyleSheetNode* _parent) : name(name)
  36. {
  37. type = _type;
  38. parent = _parent;
  39. specificity = CalculateSpecificity();
  40. selector = NULL;
  41. a = 0;
  42. b = 0;
  43. }
  44. // Constructs a structural style-sheet node.
  45. StyleSheetNode::StyleSheetNode(const String& name, StyleSheetNode* _parent, StyleSheetNodeSelector* _selector, int _a, int _b) : name(name)
  46. {
  47. type = STRUCTURAL_PSEUDO_CLASS;
  48. parent = _parent;
  49. specificity = CalculateSpecificity();
  50. selector = _selector;
  51. a = _a;
  52. b = _b;
  53. }
  54. StyleSheetNode::~StyleSheetNode()
  55. {
  56. for (int i = 0; i < NUM_NODE_TYPES; i++)
  57. {
  58. for (NodeMap::iterator j = children[i].begin(); j != children[i].end(); ++j)
  59. delete (*j).second;
  60. }
  61. }
  62. // Writes the style sheet node (and all ancestors) into the stream.
  63. void StyleSheetNode::Write(Stream* stream)
  64. {
  65. if (properties.size() > 0)
  66. {
  67. String rule;
  68. StyleSheetNode* hierarchy = this;
  69. while (hierarchy != NULL)
  70. {
  71. switch (hierarchy->type)
  72. {
  73. case TAG:
  74. rule = " " + hierarchy->name + rule;
  75. break;
  76. case CLASS:
  77. rule = "." + hierarchy->name + rule;
  78. break;
  79. case ID:
  80. rule = "#" + hierarchy->name + rule;
  81. break;
  82. case PSEUDO_CLASS:
  83. rule = ":" + hierarchy->name + rule;
  84. break;
  85. case STRUCTURAL_PSEUDO_CLASS:
  86. rule = ":" + hierarchy->name + rule;
  87. break;
  88. default:
  89. break;
  90. }
  91. hierarchy = hierarchy->parent;
  92. }
  93. stream->Write(CreateString(1024, "%s /* specificity: %d */\n", StringUtilities::StripWhitespace(rule).c_str(), specificity));
  94. stream->Write("{\n");
  95. for (const auto& [id, property] : properties)
  96. {
  97. const String& name = Rocket::Core::GetName(id);
  98. stream->Write(CreateString(1024, "\t%s: %s; /* specificity: %d */\n", name.c_str(), property.value.Get< String >().c_str(), property.specificity));
  99. }
  100. stream->Write("}\n\n");
  101. }
  102. for (size_t i = 0; i < NUM_NODE_TYPES; ++i)
  103. {
  104. for (NodeMap::iterator j = children[i].begin(); j != children[i].end(); ++j)
  105. (*j).second->Write(stream);
  106. }
  107. }
  108. // Merges an entire tree hierarchy into our hierarchy.
  109. bool StyleSheetNode::MergeHierarchy(StyleSheetNode* node, int specificity_offset)
  110. {
  111. // Merge the other node's properties into ours.
  112. MergeProperties(node->properties, specificity_offset);
  113. selector = node->selector;
  114. a = node->a;
  115. b = node->b;
  116. for (int i = 0; i < NUM_NODE_TYPES; i++)
  117. {
  118. for (NodeMap::iterator iterator = node->children[i].begin(); iterator != node->children[i].end(); ++iterator)
  119. {
  120. StyleSheetNode* local_node = GetChildNode((*iterator).second->name, (NodeType) i);
  121. local_node->MergeHierarchy((*iterator).second, specificity_offset);
  122. }
  123. }
  124. return true;
  125. }
  126. // Builds up a style sheet's index recursively.
  127. void StyleSheetNode::BuildIndex(StyleSheet::NodeIndex& styled_index, StyleSheet::NodeIndex& complete_index)
  128. {
  129. // If this is a tag node, then we insert it into the list of all tag nodes. Makes sense, neh?
  130. if (type == TAG)
  131. {
  132. StyleSheet::NodeIndex::iterator iterator = complete_index.find(name);
  133. if (iterator == complete_index.end())
  134. (*complete_index.insert(StyleSheet::NodeIndex::value_type(name, StyleSheet::NodeList())).first).second.insert(this);
  135. else
  136. (*iterator).second.insert(this);
  137. }
  138. // If we are a styled node (ie, have some style attributes attached), then we insert our closest parent tag node
  139. // into the list of styled tag nodes.
  140. if (properties.size() > 0)
  141. {
  142. StyleSheetNode* tag_node = this;
  143. while (tag_node != NULL &&
  144. tag_node->type != TAG)
  145. tag_node = tag_node->parent;
  146. if (tag_node != NULL)
  147. {
  148. StyleSheet::NodeIndex::iterator iterator = styled_index.find(tag_node->name);
  149. if (iterator == styled_index.end())
  150. (*styled_index.insert(StyleSheet::NodeIndex::value_type(tag_node->name, StyleSheet::NodeList())).first).second.insert(tag_node);
  151. else
  152. (*iterator).second.insert(tag_node);
  153. }
  154. }
  155. for (int i = 0; i < NUM_NODE_TYPES; i++)
  156. {
  157. for (NodeMap::iterator j = children[i].begin(); j != children[i].end(); ++j)
  158. (*j).second->BuildIndex(styled_index, complete_index);
  159. }
  160. }
  161. // Returns the name of this node.
  162. const String& StyleSheetNode::GetName() const
  163. {
  164. return name;
  165. }
  166. // Returns the specificity of this node.
  167. int StyleSheetNode::GetSpecificity() const
  168. {
  169. return specificity;
  170. }
  171. // Imports properties from a single rule definition (ie, with a shared specificity) into the node's
  172. // properties.
  173. void StyleSheetNode::ImportProperties(const PropertyDictionary& _properties, int rule_specificity)
  174. {
  175. Import(properties, _properties, specificity + rule_specificity);
  176. }
  177. // Merges properties from another node (ie, with potentially differing specificities) into the
  178. // node's properties.
  179. void StyleSheetNode::MergeProperties(const PropertyDictionary& _properties, int rule_specificity_offset)
  180. {
  181. Merge(properties, _properties, specificity + rule_specificity_offset);
  182. }
  183. // Returns the node's default properties.
  184. const PropertyDictionary& StyleSheetNode::GetProperties() const
  185. {
  186. return properties;
  187. }
  188. // Builds the properties of all of the pseudo-classes of this style sheet node into a single map.
  189. void StyleSheetNode::GetPseudoClassProperties(PseudoClassPropertyMap& pseudo_class_properties) const
  190. {
  191. for (NodeMap::const_iterator i = children[PSEUDO_CLASS].begin(); i != children[PSEUDO_CLASS].end(); ++i)
  192. (*i).second->GetPseudoClassProperties(pseudo_class_properties, StringList());
  193. }
  194. // Adds to a list the names of this node's pseudo-classes which are deemed volatile.
  195. bool StyleSheetNode::GetVolatilePseudoClasses(PseudoClassList& volatile_pseudo_classes) const
  196. {
  197. if (type == PSEUDO_CLASS)
  198. {
  199. bool self_volatile = !children[TAG].empty();
  200. for (NodeMap::const_iterator i = children[PSEUDO_CLASS].begin(); i != children[PSEUDO_CLASS].end(); ++i)
  201. self_volatile = (*i).second->GetVolatilePseudoClasses(volatile_pseudo_classes) | self_volatile;
  202. if (self_volatile)
  203. {
  204. if (auto it = std::find(volatile_pseudo_classes.begin(), volatile_pseudo_classes.end(), name); it == volatile_pseudo_classes.end())
  205. volatile_pseudo_classes.push_back(name);
  206. }
  207. return self_volatile;
  208. }
  209. else
  210. {
  211. for (NodeMap::const_iterator i = children[PSEUDO_CLASS].begin(); i != children[PSEUDO_CLASS].end(); ++i)
  212. (*i).second->GetVolatilePseudoClasses(volatile_pseudo_classes);
  213. }
  214. return false;
  215. }
  216. // Returns a direct child node of this node of the requested type.
  217. StyleSheetNode* StyleSheetNode::GetChildNode(const String& child_name, NodeType child_type, bool create)
  218. {
  219. // Look for a node with given name.
  220. NodeMap::iterator iterator = children[child_type].find(child_name);
  221. if (iterator != children[child_type].end())
  222. {
  223. // Traverse into node.
  224. return (*iterator).second;
  225. }
  226. else
  227. {
  228. if (create)
  229. {
  230. StyleSheetNode* new_node = NULL;
  231. // Create the node; structural pseudo-classes require a little extra leg-work.
  232. if (child_type == STRUCTURAL_PSEUDO_CLASS)
  233. new_node = CreateStructuralChild(child_name);
  234. else
  235. new_node = new StyleSheetNode(child_name, child_type, this);
  236. if (new_node != NULL)
  237. {
  238. children[child_type][child_name] = new_node;
  239. return new_node;
  240. }
  241. }
  242. return NULL;
  243. }
  244. }
  245. // Returns true if this node is applicable to the given element, given its IDs, classes and heritage.
  246. bool StyleSheetNode::IsApplicable(const Element* element) const
  247. {
  248. // This function is called with an element that matches a style node only with the tag name. We have to determine
  249. // here whether or not it also matches the required hierarchy.
  250. // We must have a parent; if not, something's amok with the style tree.
  251. if (parent == NULL)
  252. {
  253. ROCKET_ERRORMSG("Invalid RCSS hierarchy.");
  254. return false;
  255. }
  256. // If we've hit a child of the root of the style sheet tree, then we're done; no more lineage to resolve.
  257. if (parent->type == ROOT)
  258. return true;
  259. // Determine the tag (and possibly id / class as well) of the next required parent in the RCSS hierarchy.
  260. const StyleSheetNode* parent_node = parent;
  261. const String* ancestor_id = nullptr;
  262. thread_local std::vector<const String*> ancestor_classes;
  263. thread_local std::vector<const String*> ancestor_pseudo_classes;
  264. ancestor_classes.clear();
  265. ancestor_pseudo_classes.clear();
  266. std::vector< const StyleSheetNode* > ancestor_structural_pseudo_classes;
  267. while (parent_node != NULL && parent_node->type != TAG)
  268. {
  269. switch (parent_node->type)
  270. {
  271. case ID: ancestor_id = &parent_node->name; break;
  272. case CLASS: ancestor_classes.push_back(&parent_node->name); break;
  273. case PSEUDO_CLASS: ancestor_pseudo_classes.push_back(&parent_node->name); break;
  274. case STRUCTURAL_PSEUDO_CLASS: ancestor_structural_pseudo_classes.push_back(parent_node); break;
  275. default: ROCKET_ERRORMSG("Invalid RCSS hierarchy."); return false;
  276. }
  277. parent_node = parent_node->parent;
  278. }
  279. // Check for an invalid RCSS hierarchy.
  280. if (parent_node == NULL)
  281. {
  282. ROCKET_ERRORMSG("Invalid RCSS hierarchy.");
  283. return false;
  284. }
  285. // Now we know the name / class / ID / pseudo-class / structural requirements for the next ancestor requirement of
  286. // the element. So we look back through the element's ancestors to find one that matches.
  287. for (const Element* ancestor_element = element->GetParentNode(); ancestor_element != NULL; ancestor_element = ancestor_element->GetParentNode())
  288. {
  289. // Skip this ancestor if the name of the next style node doesn't match its tag name, and one was specified.
  290. if (!parent_node->name.empty()
  291. && parent_node->name != ancestor_element->GetTagName())
  292. continue;
  293. // Skip this ancestor if the ID of the next style node doesn't match its ID, and one was specified.
  294. if (ancestor_id &&
  295. *ancestor_id != ancestor_element->GetId())
  296. continue;
  297. // Skip this ancestor if the class of the next style node don't match its classes.
  298. bool resolved_requirements = true;
  299. for (size_t i = 0; i < ancestor_classes.size(); ++i)
  300. {
  301. if (!ancestor_element->IsClassSet(*ancestor_classes[i]))
  302. {
  303. resolved_requirements = false;
  304. break;
  305. }
  306. }
  307. if (!resolved_requirements)
  308. continue;
  309. // Skip this ancestor if the required pseudo-classes of the style node aren't set on it.
  310. resolved_requirements = true;
  311. for (size_t i = 0; i < ancestor_pseudo_classes.size(); ++i)
  312. {
  313. if (!ancestor_element->IsPseudoClassSet(*ancestor_pseudo_classes[i]))
  314. {
  315. resolved_requirements = false;
  316. break;
  317. }
  318. }
  319. if (!resolved_requirements)
  320. continue;
  321. // Skip this ancestor if the required structural pseudo-classes of the style node aren't applicable to it.
  322. resolved_requirements = true;
  323. for (size_t i = 0; i < ancestor_structural_pseudo_classes.size(); ++i)
  324. {
  325. if (!ancestor_structural_pseudo_classes[i]->selector->IsApplicable(ancestor_element, ancestor_structural_pseudo_classes[i]->a, ancestor_structural_pseudo_classes[i]->b))
  326. {
  327. resolved_requirements = false;
  328. break;
  329. }
  330. }
  331. if (!resolved_requirements)
  332. continue;
  333. return parent_node->IsApplicable(ancestor_element);
  334. }
  335. // We hit the end of the hierarchy before matching the required ancestor, so bail.
  336. return false;
  337. }
  338. // Appends all applicable non-tag descendants of this node into the given element list.
  339. void StyleSheetNode::GetApplicableDescendants(std::vector< const StyleSheetNode* >& applicable_nodes, const Element* element) const
  340. {
  341. // Check if this node matches this element.
  342. switch (type)
  343. {
  344. ROCKET_UNUSED_SWITCH_ENUM(NUM_NODE_TYPES);
  345. case ROOT:
  346. case TAG:
  347. {
  348. // These nodes always match.
  349. }
  350. break;
  351. case CLASS:
  352. {
  353. if (!element->IsClassSet(name))
  354. return;
  355. }
  356. break;
  357. case ID:
  358. {
  359. if (name != element->GetId())
  360. return;
  361. }
  362. break;
  363. case PSEUDO_CLASS:
  364. {
  365. if (!element->IsPseudoClassSet(name))
  366. return;
  367. }
  368. break;
  369. case STRUCTURAL_PSEUDO_CLASS:
  370. {
  371. if (selector == NULL)
  372. return;
  373. if (!selector->IsApplicable(element, a, b))
  374. return;
  375. }
  376. break;
  377. }
  378. if (properties.size() > 0 ||
  379. !children[PSEUDO_CLASS].empty())
  380. applicable_nodes.push_back(this);
  381. for (int i = CLASS; i < NUM_NODE_TYPES; i++)
  382. {
  383. // Don't recurse into pseudo-classes; they can't be built into the root definition.
  384. if (i == PSEUDO_CLASS)
  385. continue;
  386. for (NodeMap::const_iterator j = children[i].begin(); j != children[i].end(); ++j)
  387. (*j).second->GetApplicableDescendants(applicable_nodes, element);
  388. }
  389. }
  390. // Returns true if this node employs a structural selector, and therefore generates element definitions that are
  391. // sensitive to sibling changes.
  392. bool StyleSheetNode::IsStructurallyVolatile(bool check_ancestors) const
  393. {
  394. if (type == STRUCTURAL_PSEUDO_CLASS)
  395. return true;
  396. if (!children[STRUCTURAL_PSEUDO_CLASS].empty())
  397. return true;
  398. // Check our children for structural pseudo-classes.
  399. for (int i = 0; i < NUM_NODE_TYPES; ++i)
  400. {
  401. if (i == STRUCTURAL_PSEUDO_CLASS)
  402. continue;
  403. for (NodeMap::const_iterator j = children[i].begin(); j != children[i].end(); ++j)
  404. {
  405. if ((*j).second->IsStructurallyVolatile(false))
  406. return true;
  407. }
  408. }
  409. if (check_ancestors)
  410. {
  411. StyleSheetNode* ancestor = parent;
  412. while (ancestor != NULL)
  413. {
  414. if (ancestor->type == STRUCTURAL_PSEUDO_CLASS)
  415. return true;
  416. ancestor = ancestor->parent;
  417. }
  418. }
  419. return false;
  420. }
  421. // Constructs a structural pseudo-class child node.
  422. StyleSheetNode* StyleSheetNode::CreateStructuralChild(const String& child_name)
  423. {
  424. StyleSheetNodeSelector* child_selector = StyleSheetFactory::GetSelector(child_name);
  425. if (child_selector == NULL)
  426. return NULL;
  427. // Parse the 'a' and 'b' values.
  428. int child_a = 1;
  429. int child_b = 0;
  430. size_t parameter_start = child_name.find("(");
  431. size_t parameter_end = child_name.find(")");
  432. if (parameter_start != String::npos &&
  433. parameter_end != String::npos)
  434. {
  435. String parameters = child_name.substr(parameter_start + 1, parameter_end - (parameter_start + 1));
  436. // Check for 'even' or 'odd' first.
  437. if (parameters == "even")
  438. {
  439. child_a = 2;
  440. child_b = 0;
  441. }
  442. else if (parameters == "odd")
  443. {
  444. child_a = 2;
  445. child_b = 1;
  446. }
  447. else
  448. {
  449. // Alrighty; we've got an equation in the form of [[+/-]an][(+/-)b]. So, foist up, we split on 'n'.
  450. size_t n_index = parameters.find('n');
  451. if (n_index != String::npos)
  452. {
  453. // The equation is 0n + b. So a = 0, and we only have to parse b.
  454. child_a = 0;
  455. child_b = atoi(parameters.c_str());
  456. }
  457. else
  458. {
  459. if (n_index == 0)
  460. child_a = 1;
  461. else
  462. {
  463. String a_parameter = parameters.substr(0, n_index);
  464. if (StringUtilities::StripWhitespace(a_parameter) == "-")
  465. child_a = -1;
  466. else
  467. child_a = atoi(a_parameter.c_str());
  468. }
  469. if (n_index == parameters.size() - 1)
  470. child_b = 0;
  471. else
  472. child_b = atoi(parameters.substr(n_index + 1).c_str());
  473. }
  474. }
  475. }
  476. return new StyleSheetNode(child_name, this, child_selector, child_a, child_b);
  477. }
  478. // Recursively builds up a list of all pseudo-classes branching from a single node.
  479. void StyleSheetNode::GetPseudoClassProperties(PseudoClassPropertyMap& pseudo_class_properties, const StringList& ancestor_pseudo_classes)
  480. {
  481. StringList pseudo_classes(ancestor_pseudo_classes);
  482. pseudo_classes.push_back(name);
  483. if (properties.size() > 0)
  484. pseudo_class_properties[pseudo_classes] = properties;
  485. for (NodeMap::const_iterator i = children[PSEUDO_CLASS].begin(); i != children[PSEUDO_CLASS].end(); ++i)
  486. (*i).second->GetPseudoClassProperties(pseudo_class_properties, pseudo_classes);
  487. }
  488. int StyleSheetNode::CalculateSpecificity()
  489. {
  490. // Calculate the specificity of just this node; tags are worth 10,000, IDs 1,000,000 and other specifiers (classes
  491. // and pseudo-classes) 100,000.
  492. int specificity = 0;
  493. switch (type)
  494. {
  495. case TAG:
  496. {
  497. if (!name.empty())
  498. specificity = 10000;
  499. }
  500. break;
  501. case CLASS:
  502. case PSEUDO_CLASS:
  503. case STRUCTURAL_PSEUDO_CLASS:
  504. {
  505. specificity = 100000;
  506. }
  507. break;
  508. case ID:
  509. {
  510. specificity = 1000000;
  511. }
  512. break;
  513. default:
  514. {
  515. specificity = 0;
  516. }
  517. break;
  518. }
  519. // Add our parent's specificity onto ours.
  520. if (parent != NULL)
  521. specificity += parent->CalculateSpecificity();
  522. return specificity;
  523. }
  524. }
  525. }