StyleSheetNode.cpp 18 KB

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