StyleSheet.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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 our reference count on the cached element definitions.
  59. for (ElementDefinitionCache::iterator cache_iterator = address_cache.begin(); cache_iterator != address_cache.end(); ++cache_iterator)
  60. (*cache_iterator).second->RemoveReference();
  61. for (ElementDefinitionCache::iterator cache_iterator = node_cache.begin(); cache_iterator != node_cache.end(); ++cache_iterator)
  62. (*cache_iterator).second->RemoveReference();
  63. }
  64. bool StyleSheet::LoadStyleSheet(Stream* stream)
  65. {
  66. StyleSheetParser parser;
  67. specificity_offset = parser.Parse(root, stream, *this, keyframes, decorator_map, spritesheet_list);
  68. return specificity_offset >= 0;
  69. }
  70. /// Combines this style sheet with another one, producing a new sheet
  71. StyleSheet* StyleSheet::CombineStyleSheet(const StyleSheet* other_sheet) const
  72. {
  73. ROCKET_ASSERT(other_sheet);
  74. StyleSheet* new_sheet = new StyleSheet();
  75. if (!new_sheet->root->MergeHierarchy(root) ||
  76. !new_sheet->root->MergeHierarchy(other_sheet->root, specificity_offset))
  77. {
  78. delete new_sheet;
  79. return NULL;
  80. }
  81. // Any matching @keyframe names are overridden as per CSS rules
  82. new_sheet->keyframes = keyframes;
  83. for (auto& other_keyframes : other_sheet->keyframes)
  84. {
  85. new_sheet->keyframes[other_keyframes.first] = other_keyframes.second;
  86. }
  87. // Copy over the decorators, and replace any matching decorator names from other_sheet
  88. new_sheet->decorator_map = decorator_map;
  89. for (auto& other_decorator: other_sheet->decorator_map)
  90. {
  91. new_sheet->decorator_map[other_decorator.first] = other_decorator.second;
  92. }
  93. new_sheet->spritesheet_list = other_sheet->spritesheet_list;
  94. new_sheet->spritesheet_list.Merge(spritesheet_list);
  95. new_sheet->specificity_offset = specificity_offset + other_sheet->specificity_offset;
  96. return new_sheet;
  97. }
  98. // Builds the node index for a combined style sheet.
  99. void StyleSheet::BuildNodeIndexAndOptimizeProperties()
  100. {
  101. if (complete_node_index.empty())
  102. {
  103. styled_node_index.clear();
  104. complete_node_index.clear();
  105. root->BuildIndexAndOptimizeProperties(styled_node_index, complete_node_index, *this);
  106. }
  107. }
  108. // Returns the Keyframes of the given name, or null if it does not exist.
  109. Keyframes * StyleSheet::GetKeyframes(const String & name)
  110. {
  111. auto it = keyframes.find(name);
  112. if (it != keyframes.end())
  113. return &(it->second);
  114. return nullptr;
  115. }
  116. std::shared_ptr<Decorator> StyleSheet::GetDecorator(const String& name) const
  117. {
  118. auto it = decorator_map.find(name);
  119. if (it == decorator_map.end())
  120. return nullptr;
  121. return it->second.decorator;
  122. }
  123. const Sprite* StyleSheet::GetSprite(const String& name) const
  124. {
  125. return spritesheet_list.GetSprite(name);
  126. }
  127. DecoratorList StyleSheet::InstanceDecoratorsFromString(const String& decorator_string_value, const String& source_file, int source_line_number) const
  128. {
  129. // Decorators are declared as
  130. // decorator: <decorator-value>[, <decorator-value> ...];
  131. // Where <decorator-value> is either a @decorator name:
  132. // decorator: invader-theme-background, ...;
  133. // or is an anonymous decorator with inline properties
  134. // decorator: tiled-box( <shorthand properties> ), ...;
  135. DecoratorList decorator_list;
  136. if (decorator_string_value.empty() || decorator_string_value == NONE)
  137. return decorator_list;
  138. // Make sure we don't split inside the parenthesis since they may appear in decorator shorthands.
  139. StringList decorator_string_list;
  140. StringUtilities::ExpandString(decorator_string_list, decorator_string_value, ',', '(', ')');
  141. decorator_list.reserve(decorator_string_list.size());
  142. // Get or instance each decorator in the comma-separated string list
  143. for (const String& decorator_string : decorator_string_list)
  144. {
  145. const size_t shorthand_open = decorator_string.find('(');
  146. const size_t shorthand_close = decorator_string.rfind(')');
  147. const bool invalid_parenthesis = (shorthand_open == String::npos || shorthand_close == String::npos || shorthand_open >= shorthand_close);
  148. if (invalid_parenthesis)
  149. {
  150. // We found no parenthesis, that means the value must be a name of a @decorator rule, look it up
  151. std::shared_ptr<Decorator> decorator = GetDecorator(decorator_string);
  152. if (decorator)
  153. decorator_list.emplace_back(std::move(decorator));
  154. else
  155. Log::Message(Log::LT_WARNING, "Decorator name '%s' could not be found in any @decorator rule, declared at %s:%d", decorator_string.c_str(), source_file.c_str(), source_line_number);
  156. }
  157. else
  158. {
  159. // Since we have parentheses it must be an anonymous decorator with inline properties
  160. const String type = StringUtilities::StripWhitespace(decorator_string.substr(0, shorthand_open));
  161. // Check for valid decorator type
  162. DecoratorInstancer* instancer = Factory::GetDecoratorInstancer(type);
  163. if (!instancer)
  164. {
  165. Log::Message(Log::LT_WARNING, "Decorator type '%s' not found, declared at %s:%d", type.c_str(), source_file.c_str(), source_line_number);
  166. continue;
  167. }
  168. const String shorthand = decorator_string.substr(shorthand_open + 1, shorthand_close - shorthand_open - 1);
  169. const PropertySpecification& specification = instancer->GetPropertySpecification();
  170. // Parse the shorthand properties given by the 'decorator' shorthand property
  171. PropertyDictionary properties;
  172. if (!specification.ParsePropertyDeclaration(properties, "decorator", shorthand, source_file, source_line_number))
  173. {
  174. Log::Message(Log::LT_WARNING, "Could not parse decorator value '%s' at %s:%d", decorator_string.c_str(), source_file.c_str(), source_line_number);
  175. continue;
  176. }
  177. // Set unspecified values to their defaults
  178. specification.SetPropertyDefaults(properties);
  179. std::shared_ptr<Decorator> decorator = instancer->InstanceDecorator(type, properties, DecoratorInstancerInterface(*this));
  180. if (decorator)
  181. decorator_list.emplace_back(std::move(decorator));
  182. else
  183. {
  184. Log::Message(Log::LT_WARNING, "Decorator '%s' could not be instanced, declared at %s:%d", decorator_string.c_str(), source_file.c_str(), source_line_number);
  185. continue;
  186. }
  187. }
  188. }
  189. return decorator_list;
  190. }
  191. // Returns the compiled element definition for a given element hierarchy.
  192. ElementDefinition* StyleSheet::GetElementDefinition(const Element* element) const
  193. {
  194. ROCKET_ASSERT_NONRECURSIVE;
  195. // Address cache is disabled for the time being; this doesn't work since the introduction of structural
  196. // pseudo-classes.
  197. ElementDefinitionCache::iterator cache_iterator;
  198. /* String element_address = element->GetAddress();
  199. // Look the address up in the definition, see if we've processed a similar element before.
  200. cache_iterator = address_cache.find(element_address);
  201. if (cache_iterator != address_cache.end())
  202. {
  203. ElementDefinition* definition = (*cache_iterator).second;
  204. definition->AddReference();
  205. return definition;
  206. }*/
  207. // See if there are any styles defined for this element.
  208. // Using static to avoid allocations. Make sure we don't call this function recursively.
  209. static std::vector< const StyleSheetNode* > applicable_nodes;
  210. applicable_nodes.clear();
  211. String tags[] = {element->GetTagName(), ""};
  212. for (int i = 0; i < 2; i++)
  213. {
  214. NodeIndex::const_iterator iterator = styled_node_index.find(tags[i]);
  215. if (iterator != styled_node_index.end())
  216. {
  217. const NodeList& nodes = (*iterator).second;
  218. // There are! Now see if we satisfy all of their parenting requirements. What this involves is traversing the style
  219. // nodes backwards, trying to match nodes in the element's hierarchy to nodes in the style hierarchy.
  220. for (NodeList::const_iterator iterator = nodes.begin(); iterator != nodes.end(); iterator++)
  221. {
  222. if ((*iterator)->IsApplicable(element))
  223. {
  224. // Get the node to add any of its non-tag children that we match into our list.
  225. (*iterator)->GetApplicableDescendants(applicable_nodes, element);
  226. }
  227. }
  228. }
  229. }
  230. std::sort(applicable_nodes.begin(), applicable_nodes.end(), StyleSheetNodeSort);
  231. // Compile the list of volatile pseudo-classes for this element definition.
  232. PseudoClassList volatile_pseudo_classes;
  233. bool structurally_volatile = false;
  234. for (int i = 0; i < 2; ++i)
  235. {
  236. NodeIndex::const_iterator iterator = complete_node_index.find(tags[i]);
  237. if (iterator != complete_node_index.end())
  238. {
  239. const NodeList& nodes = (*iterator).second;
  240. // See if we satisfy all of the parenting requirements for each of these nodes (as in the previous loop).
  241. for (NodeList::const_iterator iterator = nodes.begin(); iterator != nodes.end(); iterator++)
  242. {
  243. structurally_volatile |= (*iterator)->IsStructurallyVolatile();
  244. if ((*iterator)->IsApplicable(element))
  245. {
  246. std::vector< const StyleSheetNode* > volatile_nodes;
  247. (*iterator)->GetApplicableDescendants(volatile_nodes, element);
  248. for (size_t i = 0; i < volatile_nodes.size(); ++i)
  249. volatile_nodes[i]->GetVolatilePseudoClasses(volatile_pseudo_classes);
  250. }
  251. }
  252. }
  253. }
  254. // If this element definition won't actually store any information, don't bother with it.
  255. if (applicable_nodes.empty() &&
  256. volatile_pseudo_classes.empty() &&
  257. !structurally_volatile)
  258. return NULL;
  259. // Check if this puppy has already been cached in the node index; it may be that it has already been created by an
  260. // element with a different address but an identical output definition.
  261. size_t seed = 0;
  262. for (const auto* node : applicable_nodes)
  263. hash_combine(seed, node);
  264. for (const String& str : volatile_pseudo_classes)
  265. hash_combine(seed, str);
  266. cache_iterator = node_cache.find(seed);
  267. if (cache_iterator != node_cache.end())
  268. {
  269. ElementDefinition* definition = (*cache_iterator).second;
  270. definition->AddReference();
  271. applicable_nodes.clear();
  272. return definition;
  273. }
  274. // Create the new definition and add it to our cache. One reference count is added, bringing the total to two; one
  275. // for the element that requested it, and one for the cache.
  276. ElementDefinition* new_definition = new ElementDefinition();
  277. new_definition->Initialise(applicable_nodes, volatile_pseudo_classes, structurally_volatile);
  278. // Add to the address cache.
  279. // address_cache[element_address] = new_definition;
  280. // new_definition->AddReference();
  281. // Add to the node cache.
  282. node_cache[seed] = new_definition;
  283. new_definition->AddReference();
  284. applicable_nodes.clear();
  285. return new_definition;
  286. }
  287. // Destroys the style sheet.
  288. void StyleSheet::OnReferenceDeactivate()
  289. {
  290. delete this;
  291. }
  292. }
  293. }