StyleSheetNode.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  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. auto it = std::find(volatile_pseudo_classes.begin(), volatile_pseudo_classes.end(), name);
  207. if (it == volatile_pseudo_classes.end())
  208. volatile_pseudo_classes.push_back(name);
  209. }
  210. return self_volatile;
  211. }
  212. else
  213. {
  214. for (NodeMap::const_iterator i = children[PSEUDO_CLASS].begin(); i != children[PSEUDO_CLASS].end(); ++i)
  215. (*i).second->GetVolatilePseudoClasses(volatile_pseudo_classes);
  216. }
  217. return false;
  218. }
  219. // Returns a direct child node of this node of the requested type.
  220. StyleSheetNode* StyleSheetNode::GetChildNode(const String& child_name, NodeType child_type, bool create)
  221. {
  222. // Look for a node with given name.
  223. NodeMap::iterator iterator = children[child_type].find(child_name);
  224. if (iterator != children[child_type].end())
  225. {
  226. // Traverse into node.
  227. return (*iterator).second;
  228. }
  229. else
  230. {
  231. if (create)
  232. {
  233. StyleSheetNode* new_node = NULL;
  234. // Create the node; structural pseudo-classes require a little extra leg-work.
  235. if (child_type == STRUCTURAL_PSEUDO_CLASS)
  236. new_node = CreateStructuralChild(child_name);
  237. else
  238. new_node = new StyleSheetNode(child_name, child_type, this);
  239. if (new_node != NULL)
  240. {
  241. children[child_type][child_name] = new_node;
  242. return new_node;
  243. }
  244. }
  245. return NULL;
  246. }
  247. }
  248. // Returns true if this node is applicable to the given element, given its IDs, classes and heritage.
  249. bool StyleSheetNode::IsApplicable(const Element* element) const
  250. {
  251. // This function is called with an element that matches a style node only with the tag name. We have to determine
  252. // here whether or not it also matches the required hierarchy.
  253. // We must have a parent; if not, something's amok with the style tree.
  254. if (parent == NULL)
  255. {
  256. ROCKET_ERRORMSG("Invalid RCSS hierarchy.");
  257. return false;
  258. }
  259. // If we've hit a child of the root of the style sheet tree, then we're done; no more lineage to resolve.
  260. if (parent->type == ROOT)
  261. return true;
  262. // Determine the tag (and possibly id / class as well) of the next required parent in the RCSS hierarchy.
  263. const StyleSheetNode* parent_node = parent;
  264. const String* ancestor_id = nullptr;
  265. static std::vector<const String*> ancestor_classes;
  266. static std::vector<const String*> ancestor_pseudo_classes;
  267. ancestor_classes.clear();
  268. ancestor_pseudo_classes.clear();
  269. std::vector< const StyleSheetNode* > ancestor_structural_pseudo_classes;
  270. while (parent_node != NULL && parent_node->type != TAG)
  271. {
  272. switch (parent_node->type)
  273. {
  274. case ID: ancestor_id = &parent_node->name; break;
  275. case CLASS: ancestor_classes.push_back(&parent_node->name); break;
  276. case PSEUDO_CLASS: ancestor_pseudo_classes.push_back(&parent_node->name); break;
  277. case STRUCTURAL_PSEUDO_CLASS: ancestor_structural_pseudo_classes.push_back(parent_node); break;
  278. default: ROCKET_ERRORMSG("Invalid RCSS hierarchy."); return false;
  279. }
  280. parent_node = parent_node->parent;
  281. }
  282. // Check for an invalid RCSS hierarchy.
  283. if (parent_node == NULL)
  284. {
  285. ROCKET_ERRORMSG("Invalid RCSS hierarchy.");
  286. return false;
  287. }
  288. // Now we know the name / class / ID / pseudo-class / structural requirements for the next ancestor requirement of
  289. // the element. So we look back through the element's ancestors to find one that matches.
  290. for (const Element* ancestor_element = element->GetParentNode(); ancestor_element != NULL; ancestor_element = ancestor_element->GetParentNode())
  291. {
  292. // Skip this ancestor if the name of the next style node doesn't match its tag name, and one was specified.
  293. if (!parent_node->name.empty()
  294. && parent_node->name != ancestor_element->GetTagName())
  295. continue;
  296. // Skip this ancestor if the ID of the next style node doesn't match its ID, and one was specified.
  297. if (ancestor_id &&
  298. *ancestor_id != ancestor_element->GetId())
  299. continue;
  300. // Skip this ancestor if the class of the next style node don't match its classes.
  301. bool resolved_requirements = true;
  302. for (size_t i = 0; i < ancestor_classes.size(); ++i)
  303. {
  304. if (!ancestor_element->IsClassSet(*ancestor_classes[i]))
  305. {
  306. resolved_requirements = false;
  307. break;
  308. }
  309. }
  310. if (!resolved_requirements)
  311. continue;
  312. // Skip this ancestor if the required pseudo-classes of the style node aren't set on it.
  313. resolved_requirements = true;
  314. for (size_t i = 0; i < ancestor_pseudo_classes.size(); ++i)
  315. {
  316. if (!ancestor_element->IsPseudoClassSet(*ancestor_pseudo_classes[i]))
  317. {
  318. resolved_requirements = false;
  319. break;
  320. }
  321. }
  322. if (!resolved_requirements)
  323. continue;
  324. // Skip this ancestor if the required structural pseudo-classes of the style node aren't applicable to it.
  325. resolved_requirements = true;
  326. for (size_t i = 0; i < ancestor_structural_pseudo_classes.size(); ++i)
  327. {
  328. if (!ancestor_structural_pseudo_classes[i]->selector->IsApplicable(ancestor_element, ancestor_structural_pseudo_classes[i]->a, ancestor_structural_pseudo_classes[i]->b))
  329. {
  330. resolved_requirements = false;
  331. break;
  332. }
  333. }
  334. if (!resolved_requirements)
  335. continue;
  336. return parent_node->IsApplicable(ancestor_element);
  337. }
  338. // We hit the end of the hierarchy before matching the required ancestor, so bail.
  339. return false;
  340. }
  341. // Appends all applicable non-tag descendants of this node into the given element list.
  342. void StyleSheetNode::GetApplicableDescendants(std::vector< const StyleSheetNode* >& applicable_nodes, const Element* element) const
  343. {
  344. // Check if this node matches this element.
  345. switch (type)
  346. {
  347. ROCKET_UNUSED_SWITCH_ENUM(NUM_NODE_TYPES);
  348. case ROOT:
  349. case TAG:
  350. {
  351. // These nodes always match.
  352. }
  353. break;
  354. case CLASS:
  355. {
  356. if (!element->IsClassSet(name))
  357. return;
  358. }
  359. break;
  360. case ID:
  361. {
  362. if (name != element->GetId())
  363. return;
  364. }
  365. break;
  366. case PSEUDO_CLASS:
  367. {
  368. if (!element->IsPseudoClassSet(name))
  369. return;
  370. }
  371. break;
  372. case STRUCTURAL_PSEUDO_CLASS:
  373. {
  374. if (selector == NULL)
  375. return;
  376. if (!selector->IsApplicable(element, a, b))
  377. return;
  378. }
  379. break;
  380. }
  381. if (properties.GetNumProperties() > 0 ||
  382. !children[PSEUDO_CLASS].empty())
  383. applicable_nodes.push_back(this);
  384. for (int i = CLASS; i < NUM_NODE_TYPES; i++)
  385. {
  386. // Don't recurse into pseudo-classes; they can't be built into the root definition.
  387. if (i == PSEUDO_CLASS)
  388. continue;
  389. for (NodeMap::const_iterator j = children[i].begin(); j != children[i].end(); ++j)
  390. (*j).second->GetApplicableDescendants(applicable_nodes, element);
  391. }
  392. }
  393. // Returns true if this node employs a structural selector, and therefore generates element definitions that are
  394. // sensitive to sibling changes.
  395. bool StyleSheetNode::IsStructurallyVolatile(bool check_ancestors) const
  396. {
  397. if (type == STRUCTURAL_PSEUDO_CLASS)
  398. return true;
  399. if (!children[STRUCTURAL_PSEUDO_CLASS].empty())
  400. return true;
  401. // Check our children for structural pseudo-classes.
  402. for (int i = 0; i < NUM_NODE_TYPES; ++i)
  403. {
  404. if (i == STRUCTURAL_PSEUDO_CLASS)
  405. continue;
  406. for (NodeMap::const_iterator j = children[i].begin(); j != children[i].end(); ++j)
  407. {
  408. if ((*j).second->IsStructurallyVolatile(false))
  409. return true;
  410. }
  411. }
  412. if (check_ancestors)
  413. {
  414. StyleSheetNode* ancestor = parent;
  415. while (ancestor != NULL)
  416. {
  417. if (ancestor->type == STRUCTURAL_PSEUDO_CLASS)
  418. return true;
  419. ancestor = ancestor->parent;
  420. }
  421. }
  422. return false;
  423. }
  424. // Constructs a structural pseudo-class child node.
  425. StyleSheetNode* StyleSheetNode::CreateStructuralChild(const String& child_name)
  426. {
  427. StyleSheetNodeSelector* child_selector = StyleSheetFactory::GetSelector(child_name);
  428. if (child_selector == NULL)
  429. return NULL;
  430. // Parse the 'a' and 'b' values.
  431. int child_a = 1;
  432. int child_b = 0;
  433. size_t parameter_start = child_name.find("(");
  434. size_t parameter_end = child_name.find(")");
  435. if (parameter_start != String::npos &&
  436. parameter_end != String::npos)
  437. {
  438. String parameters = child_name.substr(parameter_start + 1, parameter_end - (parameter_start + 1));
  439. // Check for 'even' or 'odd' first.
  440. if (parameters == "even")
  441. {
  442. child_a = 2;
  443. child_b = 0;
  444. }
  445. else if (parameters == "odd")
  446. {
  447. child_a = 2;
  448. child_b = 1;
  449. }
  450. else
  451. {
  452. // Alrighty; we've got an equation in the form of [[+/-]an][(+/-)b]. So, foist up, we split on 'n'.
  453. size_t n_index = parameters.find('n');
  454. if (n_index != String::npos)
  455. {
  456. // The equation is 0n + b. So a = 0, and we only have to parse b.
  457. child_a = 0;
  458. child_b = atoi(parameters.c_str());
  459. }
  460. else
  461. {
  462. if (n_index == 0)
  463. child_a = 1;
  464. else
  465. {
  466. String a_parameter = parameters.substr(0, n_index);
  467. if (StringUtilities::StripWhitespace(a_parameter) == "-")
  468. child_a = -1;
  469. else
  470. child_a = atoi(a_parameter.c_str());
  471. }
  472. if (n_index == parameters.size() - 1)
  473. child_b = 0;
  474. else
  475. child_b = atoi(parameters.substr(n_index + 1).c_str());
  476. }
  477. }
  478. }
  479. return new StyleSheetNode(child_name, this, child_selector, child_a, child_b);
  480. }
  481. // Recursively builds up a list of all pseudo-classes branching from a single node.
  482. void StyleSheetNode::GetPseudoClassProperties(PseudoClassPropertyMap& pseudo_class_properties, const StringList& ancestor_pseudo_classes)
  483. {
  484. StringList pseudo_classes(ancestor_pseudo_classes);
  485. pseudo_classes.push_back(name);
  486. if (properties.GetNumProperties() > 0)
  487. pseudo_class_properties[pseudo_classes] = properties;
  488. for (NodeMap::const_iterator i = children[PSEUDO_CLASS].begin(); i != children[PSEUDO_CLASS].end(); ++i)
  489. (*i).second->GetPseudoClassProperties(pseudo_class_properties, pseudo_classes);
  490. }
  491. int StyleSheetNode::CalculateSpecificity()
  492. {
  493. // Calculate the specificity of just this node; tags are worth 10,000, IDs 1,000,000 and other specifiers (classes
  494. // and pseudo-classes) 100,000.
  495. int specificity = 0;
  496. switch (type)
  497. {
  498. case TAG:
  499. {
  500. if (!name.empty())
  501. specificity = 10000;
  502. }
  503. break;
  504. case CLASS:
  505. case PSEUDO_CLASS:
  506. case STRUCTURAL_PSEUDO_CLASS:
  507. {
  508. specificity = 100000;
  509. }
  510. break;
  511. case ID:
  512. {
  513. specificity = 1000000;
  514. }
  515. break;
  516. default:
  517. {
  518. specificity = 0;
  519. }
  520. break;
  521. }
  522. // Add our parent's specificity onto ours.
  523. if (parent != NULL)
  524. specificity += parent->CalculateSpecificity();
  525. return specificity;
  526. }
  527. }
  528. }