StyleSheetNode.cpp 18 KB

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