StyleSheet.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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 "../../Include/Rocket/Core/StyleSheet.h"
  29. #include <algorithm>
  30. #include "ElementDefinition.h"
  31. #include "StyleSheetFactory.h"
  32. #include "StyleSheetNode.h"
  33. #include "StyleSheetParser.h"
  34. #include "../../Include/Rocket/Core/Element.h"
  35. #include "../../Include/Rocket/Core/PropertyDefinition.h"
  36. #include "../../Include/Rocket/Core/StyleSheetSpecification.h"
  37. namespace Rocket {
  38. namespace Core {
  39. template <class T>
  40. static inline void hash_combine(std::size_t& seed, const T& v)
  41. {
  42. std::hash<T> hasher;
  43. seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
  44. }
  45. // Sorts style nodes based on specificity.
  46. static bool StyleSheetNodeSort(const StyleSheetNode* lhs, const StyleSheetNode* rhs)
  47. {
  48. return lhs->GetSpecificity() < rhs->GetSpecificity();
  49. }
  50. StyleSheet::StyleSheet()
  51. {
  52. root = new StyleSheetNode("", StyleSheetNode::ROOT);
  53. specificity_offset = 0;
  54. }
  55. StyleSheet::~StyleSheet()
  56. {
  57. delete root;
  58. // Release decorators
  59. for (auto& pair : decorator_map)
  60. pair.second.decorator->RemoveReference();
  61. // Release our reference count on the cached element definitions.
  62. for (ElementDefinitionCache::iterator cache_iterator = address_cache.begin(); cache_iterator != address_cache.end(); ++cache_iterator)
  63. (*cache_iterator).second->RemoveReference();
  64. for (ElementDefinitionCache::iterator cache_iterator = node_cache.begin(); cache_iterator != node_cache.end(); ++cache_iterator)
  65. (*cache_iterator).second->RemoveReference();
  66. }
  67. bool StyleSheet::LoadStyleSheet(Stream* stream)
  68. {
  69. StyleSheetParser parser;
  70. specificity_offset = parser.Parse(root, stream, *this, keyframes, decorator_map, spritesheet_list);
  71. return specificity_offset >= 0;
  72. }
  73. /// Combines this style sheet with another one, producing a new sheet
  74. StyleSheet* StyleSheet::CombineStyleSheet(const StyleSheet* other_sheet) const
  75. {
  76. ROCKET_ASSERT(other_sheet);
  77. StyleSheet* new_sheet = new StyleSheet();
  78. if (!new_sheet->root->MergeHierarchy(root) ||
  79. !new_sheet->root->MergeHierarchy(other_sheet->root, specificity_offset))
  80. {
  81. delete new_sheet;
  82. return NULL;
  83. }
  84. // Any matching @keyframe names are overridden as per CSS rules
  85. new_sheet->keyframes = keyframes;
  86. for (auto& other_keyframes : other_sheet->keyframes)
  87. {
  88. new_sheet->keyframes[other_keyframes.first] = other_keyframes.second;
  89. }
  90. // Copy over the decorators, and replace any matching decorator names from other_sheet
  91. // @todo / @leak: Add and remove references as appropriate, not sufficient as is!
  92. new_sheet->decorator_map = decorator_map;
  93. for (auto& other_decorator: other_sheet->decorator_map)
  94. {
  95. new_sheet->decorator_map[other_decorator.first] = other_decorator.second;
  96. }
  97. for (auto& pair : new_sheet->decorator_map)
  98. pair.second.decorator->AddReference();
  99. new_sheet->spritesheet_list = other_sheet->spritesheet_list;
  100. new_sheet->spritesheet_list.Merge(spritesheet_list);
  101. new_sheet->specificity_offset = specificity_offset + other_sheet->specificity_offset;
  102. return new_sheet;
  103. }
  104. // Builds the node index for a combined style sheet.
  105. void StyleSheet::BuildNodeIndex()
  106. {
  107. if (complete_node_index.empty())
  108. {
  109. styled_node_index.clear();
  110. complete_node_index.clear();
  111. root->BuildIndex(styled_node_index, complete_node_index);
  112. }
  113. }
  114. // Returns the Keyframes of the given name, or null if it does not exist.
  115. Keyframes * StyleSheet::GetKeyframes(const String & name)
  116. {
  117. auto it = keyframes.find(name);
  118. if (it != keyframes.end())
  119. return &(it->second);
  120. return nullptr;
  121. }
  122. Decorator* StyleSheet::GetDecorator(const String& name) const
  123. {
  124. auto it = decorator_map.find(name);
  125. if (it == decorator_map.end())
  126. return nullptr;
  127. return it->second.decorator;
  128. }
  129. const Sprite* StyleSheet::GetSprite(const String& name) const
  130. {
  131. return spritesheet_list.GetSprite(name);
  132. }
  133. Decorator* StyleSheet::GetOrInstanceDecorator(const String& decorator_value, const String& source_file, int source_line_number)
  134. {
  135. // Try to find a decorator declared with @decorator or otherwise previously instanced shorthand decorator.
  136. auto it_find = decorator_map.find(decorator_value);
  137. if (it_find != decorator_map.end())
  138. {
  139. return it_find->second.decorator;
  140. }
  141. // The decorator does not exist, try to instance a new one from a shorthand decorator value declared as:
  142. // decorator: <type>( <shorthand> );
  143. // where <type> is the decorator type and the value <shorthand> is applied to its "decorator"-shorthand.
  144. // Check syntax
  145. size_t shorthand_open = decorator_value.find('(');
  146. size_t shorthand_close = decorator_value.rfind(')');
  147. if (shorthand_open == String::npos || shorthand_close == String::npos || shorthand_open >= shorthand_close)
  148. return nullptr;
  149. String type = StringUtilities::StripWhitespace(decorator_value.substr(0, shorthand_open));
  150. // Check for valid decorator type
  151. const PropertySpecification* specification = Factory::GetDecoratorPropertySpecification(type);
  152. if (!specification)
  153. return nullptr;
  154. String shorthand = decorator_value.substr(shorthand_open + 1, shorthand_close - shorthand_open - 1);
  155. // Parse the shorthand properties
  156. PropertyDictionary properties;
  157. if (!specification->ParsePropertyDeclaration(properties, "decorator", shorthand, source_file, source_line_number))
  158. {
  159. Log::Message(Log::LT_WARNING, "Could not parse decorator value '%s' at %s:%d", decorator_value.c_str(), source_file.c_str(), source_line_number);
  160. return nullptr;
  161. }
  162. specification->SetPropertyDefaults(properties);
  163. Decorator* decorator = Factory::InstanceDecorator(type, properties, *this);
  164. if (!decorator)
  165. return nullptr;
  166. // Insert decorator into map
  167. auto result = decorator_map.emplace(decorator_value, DecoratorSpecification{ type, properties, decorator });
  168. if (!result.second)
  169. {
  170. decorator->RemoveReference();
  171. return nullptr;
  172. }
  173. return decorator;
  174. }
  175. // Returns the compiled element definition for a given element hierarchy.
  176. ElementDefinition* StyleSheet::GetElementDefinition(const Element* element) const
  177. {
  178. ROCKET_ASSERT_NONRECURSIVE;
  179. // Address cache is disabled for the time being; this doesn't work since the introduction of structural
  180. // pseudo-classes.
  181. ElementDefinitionCache::iterator cache_iterator;
  182. /* String element_address = element->GetAddress();
  183. // Look the address up in the definition, see if we've processed a similar element before.
  184. cache_iterator = address_cache.find(element_address);
  185. if (cache_iterator != address_cache.end())
  186. {
  187. ElementDefinition* definition = (*cache_iterator).second;
  188. definition->AddReference();
  189. return definition;
  190. }*/
  191. // See if there are any styles defined for this element.
  192. // Using static to avoid allocations. Make sure we don't call this function recursively.
  193. static std::vector< const StyleSheetNode* > applicable_nodes;
  194. applicable_nodes.clear();
  195. String tags[] = {element->GetTagName(), ""};
  196. for (int i = 0; i < 2; i++)
  197. {
  198. NodeIndex::const_iterator iterator = styled_node_index.find(tags[i]);
  199. if (iterator != styled_node_index.end())
  200. {
  201. const NodeList& nodes = (*iterator).second;
  202. // There are! Now see if we satisfy all of their parenting requirements. What this involves is traversing the style
  203. // nodes backwards, trying to match nodes in the element's hierarchy to nodes in the style hierarchy.
  204. for (NodeList::const_iterator iterator = nodes.begin(); iterator != nodes.end(); iterator++)
  205. {
  206. if ((*iterator)->IsApplicable(element))
  207. {
  208. // Get the node to add any of its non-tag children that we match into our list.
  209. (*iterator)->GetApplicableDescendants(applicable_nodes, element);
  210. }
  211. }
  212. }
  213. }
  214. std::sort(applicable_nodes.begin(), applicable_nodes.end(), StyleSheetNodeSort);
  215. // Compile the list of volatile pseudo-classes for this element definition.
  216. PseudoClassList volatile_pseudo_classes;
  217. bool structurally_volatile = false;
  218. for (int i = 0; i < 2; ++i)
  219. {
  220. NodeIndex::const_iterator iterator = complete_node_index.find(tags[i]);
  221. if (iterator != complete_node_index.end())
  222. {
  223. const NodeList& nodes = (*iterator).second;
  224. // See if we satisfy all of the parenting requirements for each of these nodes (as in the previous loop).
  225. for (NodeList::const_iterator iterator = nodes.begin(); iterator != nodes.end(); iterator++)
  226. {
  227. structurally_volatile |= (*iterator)->IsStructurallyVolatile();
  228. if ((*iterator)->IsApplicable(element))
  229. {
  230. std::vector< const StyleSheetNode* > volatile_nodes;
  231. (*iterator)->GetApplicableDescendants(volatile_nodes, element);
  232. for (size_t i = 0; i < volatile_nodes.size(); ++i)
  233. volatile_nodes[i]->GetVolatilePseudoClasses(volatile_pseudo_classes);
  234. }
  235. }
  236. }
  237. }
  238. // If this element definition won't actually store any information, don't bother with it.
  239. if (applicable_nodes.empty() &&
  240. volatile_pseudo_classes.empty() &&
  241. !structurally_volatile)
  242. return NULL;
  243. // Check if this puppy has already been cached in the node index; it may be that it has already been created by an
  244. // element with a different address but an identical output definition.
  245. size_t seed = 0;
  246. for (const auto* node : applicable_nodes)
  247. hash_combine(seed, node);
  248. for (const String& str : volatile_pseudo_classes)
  249. hash_combine(seed, str);
  250. cache_iterator = node_cache.find(seed);
  251. if (cache_iterator != node_cache.end())
  252. {
  253. ElementDefinition* definition = (*cache_iterator).second;
  254. definition->AddReference();
  255. applicable_nodes.clear();
  256. return definition;
  257. }
  258. // Create the new definition and add it to our cache. One reference count is added, bringing the total to two; one
  259. // for the element that requested it, and one for the cache.
  260. ElementDefinition* new_definition = new ElementDefinition();
  261. new_definition->Initialise(applicable_nodes, volatile_pseudo_classes, structurally_volatile);
  262. // Add to the address cache.
  263. // address_cache[element_address] = new_definition;
  264. // new_definition->AddReference();
  265. // Add to the node cache.
  266. node_cache[seed] = new_definition;
  267. new_definition->AddReference();
  268. applicable_nodes.clear();
  269. return new_definition;
  270. }
  271. // Destroys the style sheet.
  272. void StyleSheet::OnReferenceDeactivate()
  273. {
  274. delete this;
  275. }
  276. }
  277. }