StyleSheetNode.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  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.GetNumProperties() > 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. const Rocket::Core::PropertyMap& property_map = properties.GetProperties();
  96. for (Rocket::Core::PropertyMap::const_iterator i = property_map.begin(); i != property_map.end(); ++i)
  97. {
  98. const String& name = i->first;
  99. const Rocket::Core::Property& property = i->second;
  100. stream->Write(CreateString(1024, "\t%s: %s; /* specificity: %d */\n", name.c_str(), property.value.Get< String >().c_str(), property.specificity));
  101. }
  102. stream->Write("}\n\n");
  103. }
  104. for (size_t i = 0; i < NUM_NODE_TYPES; ++i)
  105. {
  106. for (NodeMap::iterator j = children[i].begin(); j != children[i].end(); ++j)
  107. (*j).second->Write(stream);
  108. }
  109. }
  110. // Merges an entire tree hierarchy into our hierarchy.
  111. bool StyleSheetNode::MergeHierarchy(StyleSheetNode* node, int specificity_offset)
  112. {
  113. // Merge the other node's properties into ours.
  114. MergeProperties(node->properties, specificity_offset);
  115. selector = node->selector;
  116. a = node->a;
  117. b = node->b;
  118. for (int i = 0; i < NUM_NODE_TYPES; i++)
  119. {
  120. for (NodeMap::iterator iterator = node->children[i].begin(); iterator != node->children[i].end(); ++iterator)
  121. {
  122. StyleSheetNode* local_node = GetChildNode((*iterator).second->name, (NodeType) i);
  123. local_node->MergeHierarchy((*iterator).second, specificity_offset);
  124. }
  125. }
  126. return true;
  127. }
  128. // Builds up a style sheet's index recursively.
  129. void StyleSheetNode::BuildIndex(StyleSheet::NodeIndex& styled_index, StyleSheet::NodeIndex& complete_index)
  130. {
  131. // If this is a tag node, then we insert it into the list of all tag nodes. Makes sense, neh?
  132. if (type == TAG)
  133. {
  134. StyleSheet::NodeIndex::iterator iterator = complete_index.find(name);
  135. if (iterator == complete_index.end())
  136. (*complete_index.insert(StyleSheet::NodeIndex::value_type(name, StyleSheet::NodeList())).first).second.insert(this);
  137. else
  138. (*iterator).second.insert(this);
  139. }
  140. // If we are a styled node (ie, have some style attributes attached), then we insert our closest parent tag node
  141. // into the list of styled tag nodes.
  142. if (properties.GetNumProperties() > 0)
  143. {
  144. StyleSheetNode* tag_node = this;
  145. while (tag_node != NULL &&
  146. tag_node->type != TAG)
  147. tag_node = tag_node->parent;
  148. if (tag_node != NULL)
  149. {
  150. StyleSheet::NodeIndex::iterator iterator = styled_index.find(tag_node->name);
  151. if (iterator == styled_index.end())
  152. (*styled_index.insert(StyleSheet::NodeIndex::value_type(tag_node->name, StyleSheet::NodeList())).first).second.insert(tag_node);
  153. else
  154. (*iterator).second.insert(tag_node);
  155. }
  156. }
  157. for (int i = 0; i < NUM_NODE_TYPES; i++)
  158. {
  159. for (NodeMap::iterator j = children[i].begin(); j != children[i].end(); ++j)
  160. (*j).second->BuildIndex(styled_index, complete_index);
  161. }
  162. }
  163. // Returns the name of this node.
  164. const String& StyleSheetNode::GetName() const
  165. {
  166. return name;
  167. }
  168. // Returns the specificity of this node.
  169. int StyleSheetNode::GetSpecificity() const
  170. {
  171. return specificity;
  172. }
  173. // Imports properties from a single rule definition (ie, with a shared specificity) into the node's
  174. // properties.
  175. void StyleSheetNode::ImportProperties(const PropertyDictionary& _properties, int rule_specificity)
  176. {
  177. properties.Import(_properties, specificity + rule_specificity);
  178. }
  179. // Merges properties from another node (ie, with potentially differing specificities) into the
  180. // node's properties.
  181. void StyleSheetNode::MergeProperties(const PropertyDictionary& _properties, int rule_specificity_offset)
  182. {
  183. properties.Merge(_properties, rule_specificity_offset);
  184. }
  185. // Returns the node's default properties.
  186. const PropertyDictionary& StyleSheetNode::GetProperties() const
  187. {
  188. return properties;
  189. }
  190. // Builds the properties of all of the pseudo-classes of this style sheet node into a single map.
  191. void StyleSheetNode::GetPseudoClassProperties(PseudoClassPropertyMap& pseudo_class_properties) const
  192. {
  193. for (NodeMap::const_iterator i = children[PSEUDO_CLASS].begin(); i != children[PSEUDO_CLASS].end(); ++i)
  194. (*i).second->GetPseudoClassProperties(pseudo_class_properties, StringList());
  195. }
  196. // Adds to a list the names of this node's pseudo-classes which are deemed volatile.
  197. bool StyleSheetNode::GetVolatilePseudoClasses(PseudoClassList& volatile_pseudo_classes) const
  198. {
  199. if (type == PSEUDO_CLASS)
  200. {
  201. bool self_volatile = !children[TAG].empty();
  202. for (NodeMap::const_iterator i = children[PSEUDO_CLASS].begin(); i != children[PSEUDO_CLASS].end(); ++i)
  203. self_volatile = (*i).second->GetVolatilePseudoClasses(volatile_pseudo_classes) | self_volatile;
  204. if (self_volatile)
  205. {
  206. if (auto it = std::find(volatile_pseudo_classes.begin(), volatile_pseudo_classes.end(), name); it == volatile_pseudo_classes.end())
  207. volatile_pseudo_classes.push_back(name);
  208. }
  209. return self_volatile;
  210. }
  211. else
  212. {
  213. for (NodeMap::const_iterator i = children[PSEUDO_CLASS].begin(); i != children[PSEUDO_CLASS].end(); ++i)
  214. (*i).second->GetVolatilePseudoClasses(volatile_pseudo_classes);
  215. }
  216. return false;
  217. }
  218. // Returns a direct child node of this node of the requested type.
  219. StyleSheetNode* StyleSheetNode::GetChildNode(const String& child_name, NodeType child_type, bool create)
  220. {
  221. // Look for a node with given name.
  222. NodeMap::iterator iterator = children[child_type].find(child_name);
  223. if (iterator != children[child_type].end())
  224. {
  225. // Traverse into node.
  226. return (*iterator).second;
  227. }
  228. else
  229. {
  230. if (create)
  231. {
  232. StyleSheetNode* new_node = NULL;
  233. // Create the node; structural pseudo-classes require a little extra leg-work.
  234. if (child_type == STRUCTURAL_PSEUDO_CLASS)
  235. new_node = CreateStructuralChild(child_name);
  236. else
  237. new_node = new StyleSheetNode(child_name, child_type, this);
  238. if (new_node != NULL)
  239. {
  240. children[child_type][child_name] = new_node;
  241. return new_node;
  242. }
  243. }
  244. return NULL;
  245. }
  246. }
  247. // Returns true if this node is applicable to the given element, given its IDs, classes and heritage.
  248. bool StyleSheetNode::IsApplicable(const Element* element) const
  249. {
  250. // This function is called with an element that matches a style node only with the tag name. We have to determine
  251. // here whether or not it also matches the required hierarchy.
  252. // We must have a parent; if not, something's amok with the style tree.
  253. if (parent == NULL)
  254. {
  255. ROCKET_ERRORMSG("Invalid RCSS hierarchy.");
  256. return false;
  257. }
  258. // If we've hit a child of the root of the style sheet tree, then we're done; no more lineage to resolve.
  259. if (parent->type == ROOT)
  260. return true;
  261. // Determine the tag (and possibly id / class as well) of the next required parent in the RCSS hierarchy.
  262. const StyleSheetNode* parent_node = parent;
  263. const String* ancestor_id = nullptr;
  264. static std::vector<const String*> ancestor_classes;
  265. static std::vector<const String*> ancestor_pseudo_classes;
  266. ancestor_classes.clear();
  267. ancestor_pseudo_classes.clear();
  268. std::vector< const StyleSheetNode* > ancestor_structural_pseudo_classes;
  269. while (parent_node != NULL && parent_node->type != TAG)
  270. {
  271. switch (parent_node->type)
  272. {
  273. case ID: ancestor_id = &parent_node->name; break;
  274. case CLASS: ancestor_classes.push_back(&parent_node->name); break;
  275. case PSEUDO_CLASS: ancestor_pseudo_classes.push_back(&parent_node->name); break;
  276. case STRUCTURAL_PSEUDO_CLASS: ancestor_structural_pseudo_classes.push_back(parent_node); break;
  277. default: ROCKET_ERRORMSG("Invalid RCSS hierarchy."); return false;
  278. }
  279. parent_node = parent_node->parent;
  280. }
  281. // Check for an invalid RCSS hierarchy.
  282. if (parent_node == NULL)
  283. {
  284. ROCKET_ERRORMSG("Invalid RCSS hierarchy.");
  285. return false;
  286. }
  287. // Now we know the name / class / ID / pseudo-class / structural requirements for the next ancestor requirement of
  288. // the element. So we look back through the element's ancestors to find one that matches.
  289. for (const Element* ancestor_element = element->GetParentNode(); ancestor_element != NULL; ancestor_element = ancestor_element->GetParentNode())
  290. {
  291. // Skip this ancestor if the name of the next style node doesn't match its tag name, and one was specified.
  292. if (!parent_node->name.empty()
  293. && parent_node->name != ancestor_element->GetTagName())
  294. continue;
  295. // Skip this ancestor if the ID of the next style node doesn't match its ID, and one was specified.
  296. if (ancestor_id &&
  297. *ancestor_id != ancestor_element->GetId())
  298. continue;
  299. // Skip this ancestor if the class of the next style node don't match its classes.
  300. bool resolved_requirements = true;
  301. for (size_t i = 0; i < ancestor_classes.size(); ++i)
  302. {
  303. if (!ancestor_element->IsClassSet(*ancestor_classes[i]))
  304. {
  305. resolved_requirements = false;
  306. break;
  307. }
  308. }
  309. if (!resolved_requirements)
  310. continue;
  311. // Skip this ancestor if the required pseudo-classes of the style node aren't set on it.
  312. resolved_requirements = true;
  313. for (size_t i = 0; i < ancestor_pseudo_classes.size(); ++i)
  314. {
  315. if (!ancestor_element->IsPseudoClassSet(*ancestor_pseudo_classes[i]))
  316. {
  317. resolved_requirements = false;
  318. break;
  319. }
  320. }
  321. if (!resolved_requirements)
  322. continue;
  323. // Skip this ancestor if the required structural pseudo-classes of the style node aren't applicable to it.
  324. resolved_requirements = true;
  325. for (size_t i = 0; i < ancestor_structural_pseudo_classes.size(); ++i)
  326. {
  327. if (!ancestor_structural_pseudo_classes[i]->selector->IsApplicable(ancestor_element, ancestor_structural_pseudo_classes[i]->a, ancestor_structural_pseudo_classes[i]->b))
  328. {
  329. resolved_requirements = false;
  330. break;
  331. }
  332. }
  333. if (!resolved_requirements)
  334. continue;
  335. return parent_node->IsApplicable(ancestor_element);
  336. }
  337. // We hit the end of the hierarchy before matching the required ancestor, so bail.
  338. return false;
  339. }
  340. // Appends all applicable non-tag descendants of this node into the given element list.
  341. void StyleSheetNode::GetApplicableDescendants(std::vector< const StyleSheetNode* >& applicable_nodes, const Element* element) const
  342. {
  343. // Check if this node matches this element.
  344. switch (type)
  345. {
  346. ROCKET_UNUSED_SWITCH_ENUM(NUM_NODE_TYPES);
  347. case ROOT:
  348. case TAG:
  349. {
  350. // These nodes always match.
  351. }
  352. break;
  353. case CLASS:
  354. {
  355. if (!element->IsClassSet(name))
  356. return;
  357. }
  358. break;
  359. case ID:
  360. {
  361. if (name != element->GetId())
  362. return;
  363. }
  364. break;
  365. case PSEUDO_CLASS:
  366. {
  367. if (!element->IsPseudoClassSet(name))
  368. return;
  369. }
  370. break;
  371. case STRUCTURAL_PSEUDO_CLASS:
  372. {
  373. if (selector == NULL)
  374. return;
  375. if (!selector->IsApplicable(element, a, b))
  376. return;
  377. }
  378. break;
  379. }
  380. if (properties.GetNumProperties() > 0 ||
  381. !children[PSEUDO_CLASS].empty())
  382. applicable_nodes.push_back(this);
  383. for (int i = CLASS; i < NUM_NODE_TYPES; i++)
  384. {
  385. // Don't recurse into pseudo-classes; they can't be built into the root definition.
  386. if (i == PSEUDO_CLASS)
  387. continue;
  388. for (NodeMap::const_iterator j = children[i].begin(); j != children[i].end(); ++j)
  389. (*j).second->GetApplicableDescendants(applicable_nodes, element);
  390. }
  391. }
  392. // Returns true if this node employs a structural selector, and therefore generates element definitions that are
  393. // sensitive to sibling changes.
  394. bool StyleSheetNode::IsStructurallyVolatile(bool check_ancestors) const
  395. {
  396. if (type == STRUCTURAL_PSEUDO_CLASS)
  397. return true;
  398. if (!children[STRUCTURAL_PSEUDO_CLASS].empty())
  399. return true;
  400. // Check our children for structural pseudo-classes.
  401. for (int i = 0; i < NUM_NODE_TYPES; ++i)
  402. {
  403. if (i == STRUCTURAL_PSEUDO_CLASS)
  404. continue;
  405. for (NodeMap::const_iterator j = children[i].begin(); j != children[i].end(); ++j)
  406. {
  407. if ((*j).second->IsStructurallyVolatile(false))
  408. return true;
  409. }
  410. }
  411. if (check_ancestors)
  412. {
  413. StyleSheetNode* ancestor = parent;
  414. while (ancestor != NULL)
  415. {
  416. if (ancestor->type == STRUCTURAL_PSEUDO_CLASS)
  417. return true;
  418. ancestor = ancestor->parent;
  419. }
  420. }
  421. return false;
  422. }
  423. // Constructs a structural pseudo-class child node.
  424. StyleSheetNode* StyleSheetNode::CreateStructuralChild(const String& child_name)
  425. {
  426. StyleSheetNodeSelector* child_selector = StyleSheetFactory::GetSelector(child_name);
  427. if (child_selector == NULL)
  428. return NULL;
  429. // Parse the 'a' and 'b' values.
  430. int child_a = 1;
  431. int child_b = 0;
  432. size_t parameter_start = child_name.find("(");
  433. size_t parameter_end = child_name.find(")");
  434. if (parameter_start != String::npos &&
  435. parameter_end != String::npos)
  436. {
  437. String parameters = child_name.substr(parameter_start + 1, parameter_end - (parameter_start + 1));
  438. // Check for 'even' or 'odd' first.
  439. if (parameters == "even")
  440. {
  441. child_a = 2;
  442. child_b = 0;
  443. }
  444. else if (parameters == "odd")
  445. {
  446. child_a = 2;
  447. child_b = 1;
  448. }
  449. else
  450. {
  451. // Alrighty; we've got an equation in the form of [[+/-]an][(+/-)b]. So, foist up, we split on 'n'.
  452. size_t n_index = parameters.find('n');
  453. if (n_index != String::npos)
  454. {
  455. // The equation is 0n + b. So a = 0, and we only have to parse b.
  456. child_a = 0;
  457. child_b = atoi(parameters.c_str());
  458. }
  459. else
  460. {
  461. if (n_index == 0)
  462. child_a = 1;
  463. else
  464. {
  465. String a_parameter = parameters.substr(0, n_index);
  466. if (StringUtilities::StripWhitespace(a_parameter) == "-")
  467. child_a = -1;
  468. else
  469. child_a = atoi(a_parameter.c_str());
  470. }
  471. if (n_index == parameters.size() - 1)
  472. child_b = 0;
  473. else
  474. child_b = atoi(parameters.substr(n_index + 1).c_str());
  475. }
  476. }
  477. }
  478. return new StyleSheetNode(child_name, this, child_selector, child_a, child_b);
  479. }
  480. // Recursively builds up a list of all pseudo-classes branching from a single node.
  481. void StyleSheetNode::GetPseudoClassProperties(PseudoClassPropertyMap& pseudo_class_properties, const StringList& ancestor_pseudo_classes)
  482. {
  483. StringList pseudo_classes(ancestor_pseudo_classes);
  484. pseudo_classes.push_back(name);
  485. if (properties.GetNumProperties() > 0)
  486. pseudo_class_properties[pseudo_classes] = properties;
  487. for (NodeMap::const_iterator i = children[PSEUDO_CLASS].begin(); i != children[PSEUDO_CLASS].end(); ++i)
  488. (*i).second->GetPseudoClassProperties(pseudo_class_properties, pseudo_classes);
  489. }
  490. int StyleSheetNode::CalculateSpecificity()
  491. {
  492. // Calculate the specificity of just this node; tags are worth 10,000, IDs 1,000,000 and other specifiers (classes
  493. // and pseudo-classes) 100,000.
  494. int specificity = 0;
  495. switch (type)
  496. {
  497. case TAG:
  498. {
  499. if (!name.empty())
  500. specificity = 10000;
  501. }
  502. break;
  503. case CLASS:
  504. case PSEUDO_CLASS:
  505. case STRUCTURAL_PSEUDO_CLASS:
  506. {
  507. specificity = 100000;
  508. }
  509. break;
  510. case ID:
  511. {
  512. specificity = 1000000;
  513. }
  514. break;
  515. default:
  516. {
  517. specificity = 0;
  518. }
  519. break;
  520. }
  521. // Add our parent's specificity onto ours.
  522. if (parent != NULL)
  523. specificity += parent->CalculateSpecificity();
  524. return specificity;
  525. }
  526. }
  527. }