StyleSheet.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. /*
  2. * This source file is part of RmlUi, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://github.com/mikke89/RmlUi
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. * Copyright (c) 2019 The RmlUi Team, and contributors
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. */
  28. #include "precompiled.h"
  29. #include "../../Include/RmlUi/Core/StyleSheet.h"
  30. #include <algorithm>
  31. #include "ElementDefinition.h"
  32. #include "StyleSheetFactory.h"
  33. #include "StyleSheetNode.h"
  34. #include "StyleSheetParser.h"
  35. #include "../../Include/RmlUi/Core/Element.h"
  36. #include "../../Include/RmlUi/Core/PropertyDefinition.h"
  37. #include "../../Include/RmlUi/Core/StyleSheetSpecification.h"
  38. namespace Rml {
  39. namespace Core {
  40. template <class T>
  41. static inline void hash_combine(std::size_t& seed, const T& v)
  42. {
  43. std::hash<T> hasher;
  44. seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
  45. }
  46. // Sorts style nodes based on specificity.
  47. static bool StyleSheetNodeSort(const StyleSheetNode* lhs, const StyleSheetNode* rhs)
  48. {
  49. return lhs->GetSpecificity() < rhs->GetSpecificity();
  50. }
  51. StyleSheet::StyleSheet()
  52. {
  53. root = new StyleSheetNode("", StyleSheetNode::ROOT);
  54. specificity_offset = 0;
  55. }
  56. StyleSheet::~StyleSheet()
  57. {
  58. delete root;
  59. for (ElementDefinitionCache::iterator cache_iterator = node_cache.begin(); cache_iterator != node_cache.end(); ++cache_iterator)
  60. (*cache_iterator).second->RemoveReference();
  61. }
  62. bool StyleSheet::LoadStyleSheet(Stream* stream)
  63. {
  64. StyleSheetParser parser;
  65. specificity_offset = parser.Parse(root, stream, *this, keyframes, decorator_map, spritesheet_list);
  66. return specificity_offset >= 0;
  67. }
  68. /// Combines this style sheet with another one, producing a new sheet
  69. StyleSheet* StyleSheet::CombineStyleSheet(const StyleSheet* other_sheet) const
  70. {
  71. RMLUI_ASSERT(other_sheet);
  72. StyleSheet* new_sheet = new StyleSheet();
  73. if (!new_sheet->root->MergeHierarchy(root) ||
  74. !new_sheet->root->MergeHierarchy(other_sheet->root, specificity_offset))
  75. {
  76. delete new_sheet;
  77. return NULL;
  78. }
  79. // Any matching @keyframe names are overridden as per CSS rules
  80. new_sheet->keyframes = keyframes;
  81. for (auto& other_keyframes : other_sheet->keyframes)
  82. {
  83. new_sheet->keyframes[other_keyframes.first] = other_keyframes.second;
  84. }
  85. // Copy over the decorators, and replace any matching decorator names from other_sheet
  86. new_sheet->decorator_map = decorator_map;
  87. for (auto& other_decorator: other_sheet->decorator_map)
  88. {
  89. new_sheet->decorator_map[other_decorator.first] = other_decorator.second;
  90. }
  91. new_sheet->spritesheet_list = other_sheet->spritesheet_list;
  92. new_sheet->spritesheet_list.Merge(spritesheet_list);
  93. new_sheet->specificity_offset = specificity_offset + other_sheet->specificity_offset;
  94. return new_sheet;
  95. }
  96. // Builds the node index for a combined style sheet.
  97. void StyleSheet::BuildNodeIndexAndOptimizeProperties()
  98. {
  99. if (complete_node_index.empty())
  100. {
  101. styled_node_index.clear();
  102. complete_node_index.clear();
  103. root->BuildIndexAndOptimizeProperties(styled_node_index, complete_node_index, *this);
  104. root->SetStructurallyVolatileRecursive(false);
  105. }
  106. }
  107. // Returns the Keyframes of the given name, or null if it does not exist.
  108. Keyframes * StyleSheet::GetKeyframes(const String & name)
  109. {
  110. auto it = keyframes.find(name);
  111. if (it != keyframes.end())
  112. return &(it->second);
  113. return nullptr;
  114. }
  115. std::shared_ptr<Decorator> StyleSheet::GetDecorator(const String& name) const
  116. {
  117. auto it = decorator_map.find(name);
  118. if (it == decorator_map.end())
  119. return nullptr;
  120. return it->second.decorator;
  121. }
  122. const Sprite* StyleSheet::GetSprite(const String& name) const
  123. {
  124. return spritesheet_list.GetSprite(name);
  125. }
  126. DecoratorList StyleSheet::InstanceDecoratorsFromString(const String& decorator_string_value, const String& source_file, int source_line_number) const
  127. {
  128. // Decorators are declared as
  129. // decorator: <decorator-value>[, <decorator-value> ...];
  130. // Where <decorator-value> is either a @decorator name:
  131. // decorator: invader-theme-background, ...;
  132. // or is an anonymous decorator with inline properties
  133. // decorator: tiled-box( <shorthand properties> ), ...;
  134. DecoratorList decorator_list;
  135. if (decorator_string_value.empty() || decorator_string_value == NONE)
  136. return decorator_list;
  137. // Make sure we don't split inside the parenthesis since they may appear in decorator shorthands.
  138. StringList decorator_string_list;
  139. StringUtilities::ExpandString(decorator_string_list, decorator_string_value, ',', '(', ')');
  140. decorator_list.reserve(decorator_string_list.size());
  141. // Get or instance each decorator in the comma-separated string list
  142. for (const String& decorator_string : decorator_string_list)
  143. {
  144. const size_t shorthand_open = decorator_string.find('(');
  145. const size_t shorthand_close = decorator_string.rfind(')');
  146. const bool invalid_parenthesis = (shorthand_open == String::npos || shorthand_close == String::npos || shorthand_open >= shorthand_close);
  147. if (invalid_parenthesis)
  148. {
  149. // We found no parenthesis, that means the value must be a name of a @decorator rule, look it up
  150. std::shared_ptr<Decorator> decorator = GetDecorator(decorator_string);
  151. if (decorator)
  152. decorator_list.emplace_back(std::move(decorator));
  153. else
  154. 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);
  155. }
  156. else
  157. {
  158. // Since we have parentheses it must be an anonymous decorator with inline properties
  159. const String type = StringUtilities::StripWhitespace(decorator_string.substr(0, shorthand_open));
  160. // Check for valid decorator type
  161. DecoratorInstancer* instancer = Factory::GetDecoratorInstancer(type);
  162. if (!instancer)
  163. {
  164. Log::Message(Log::LT_WARNING, "Decorator type '%s' not found, declared at %s:%d", type.c_str(), source_file.c_str(), source_line_number);
  165. continue;
  166. }
  167. const String shorthand = decorator_string.substr(shorthand_open + 1, shorthand_close - shorthand_open - 1);
  168. const PropertySpecification& specification = instancer->GetPropertySpecification();
  169. // Parse the shorthand properties given by the 'decorator' shorthand property
  170. PropertyDictionary properties;
  171. if (!specification.ParsePropertyDeclaration(properties, "decorator", shorthand, source_file, source_line_number))
  172. {
  173. 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);
  174. continue;
  175. }
  176. // Set unspecified values to their defaults
  177. specification.SetPropertyDefaults(properties);
  178. std::shared_ptr<Decorator> decorator = instancer->InstanceDecorator(type, properties, DecoratorInstancerInterface(*this));
  179. if (decorator)
  180. decorator_list.emplace_back(std::move(decorator));
  181. else
  182. {
  183. 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);
  184. continue;
  185. }
  186. }
  187. }
  188. return decorator_list;
  189. }
  190. // Returns the compiled element definition for a given element hierarchy.
  191. ElementDefinition* StyleSheet::GetElementDefinition(const Element* element) const
  192. {
  193. RMLUI_ASSERT_NONRECURSIVE;
  194. // See if there are any styles defined for this element.
  195. // Using static to avoid allocations. Make sure we don't call this function recursively.
  196. static std::vector< const StyleSheetNode* > applicable_nodes;
  197. applicable_nodes.clear();
  198. String tags[] = {element->GetTagName(), ""};
  199. for (int i = 0; i < 2; i++)
  200. {
  201. auto it_nodes = styled_node_index.find(tags[i]);
  202. if (it_nodes != styled_node_index.end())
  203. {
  204. const NodeList& nodes = it_nodes->second;
  205. // There are! Now see if we satisfy all of their parenting requirements. What this involves is traversing the style
  206. // nodes backwards, trying to match nodes in the element's hierarchy to nodes in the style hierarchy.
  207. for (StyleSheetNode* node : nodes)
  208. {
  209. if (node->IsApplicable(element))
  210. {
  211. // Get the node to add any of its non-tag children that we match into our list.
  212. node->GetApplicableDescendants(applicable_nodes, element);
  213. }
  214. }
  215. }
  216. }
  217. std::sort(applicable_nodes.begin(), applicable_nodes.end(), StyleSheetNodeSort);
  218. // If this element definition won't actually store any information, don't bother with it.
  219. if (applicable_nodes.empty())
  220. return NULL;
  221. // Check if this puppy has already been cached in the node index; it may be that it has already been created by an
  222. // element with a different address but an identical output definition.
  223. size_t seed = 0;
  224. for (const auto* node : applicable_nodes)
  225. hash_combine(seed, node);
  226. auto cache_iterator = node_cache.find(seed);
  227. if (cache_iterator != node_cache.end())
  228. {
  229. ElementDefinition* definition = (*cache_iterator).second;
  230. definition->AddReference();
  231. applicable_nodes.clear();
  232. return definition;
  233. }
  234. // Create the new definition and add it to our cache. One reference count is added, bringing the total to two; one
  235. // for the element that requested it, and one for the cache.
  236. ElementDefinition* new_definition = new ElementDefinition(applicable_nodes);
  237. // Add to the node cache.
  238. node_cache[seed] = new_definition;
  239. new_definition->AddReference();
  240. return new_definition;
  241. }
  242. // Destroys the style sheet.
  243. void StyleSheet::OnReferenceDeactivate()
  244. {
  245. delete this;
  246. }
  247. }
  248. }