StyleSheet.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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 "Utilities.h"
  36. #include "../../Include/RmlUi/Core/Element.h"
  37. #include "../../Include/RmlUi/Core/PropertyDefinition.h"
  38. #include "../../Include/RmlUi/Core/StyleSheetSpecification.h"
  39. #include "../../Include/RmlUi/Core/FontEffectInstancer.h"
  40. namespace Rml {
  41. namespace Core {
  42. // Sorts style nodes based on specificity.
  43. static bool StyleSheetNodeSort(const StyleSheetNode* lhs, const StyleSheetNode* rhs)
  44. {
  45. return lhs->GetSpecificity() < rhs->GetSpecificity();
  46. }
  47. StyleSheet::StyleSheet()
  48. {
  49. root = std::make_unique<StyleSheetNode>("", StyleSheetNode::ROOT);
  50. specificity_offset = 0;
  51. }
  52. StyleSheet::~StyleSheet()
  53. {
  54. }
  55. bool StyleSheet::LoadStyleSheet(Stream* stream)
  56. {
  57. StyleSheetParser parser;
  58. specificity_offset = parser.Parse(root.get(), stream, *this, keyframes, decorator_map, spritesheet_list);
  59. return specificity_offset >= 0;
  60. }
  61. /// Combines this style sheet with another one, producing a new sheet
  62. SharedPtr<StyleSheet> StyleSheet::CombineStyleSheet(const StyleSheet& other_sheet) const
  63. {
  64. SharedPtr<StyleSheet> new_sheet = std::make_shared<StyleSheet>();
  65. if (!new_sheet->root->MergeHierarchy(root.get()) ||
  66. !new_sheet->root->MergeHierarchy(other_sheet.root.get(), specificity_offset))
  67. {
  68. return nullptr;
  69. }
  70. // Any matching @keyframe names are overridden as per CSS rules
  71. new_sheet->keyframes.reserve(keyframes.size() + other_sheet.keyframes.size());
  72. new_sheet->keyframes = keyframes;
  73. for (auto& other_keyframes : other_sheet.keyframes)
  74. {
  75. new_sheet->keyframes[other_keyframes.first] = other_keyframes.second;
  76. }
  77. // Copy over the decorators, and replace any matching decorator names from other_sheet
  78. new_sheet->decorator_map.reserve(decorator_map.size() + other_sheet.decorator_map.size());
  79. new_sheet->decorator_map = decorator_map;
  80. for (auto& other_decorator: other_sheet.decorator_map)
  81. {
  82. new_sheet->decorator_map[other_decorator.first] = other_decorator.second;
  83. }
  84. new_sheet->spritesheet_list.Reserve(
  85. spritesheet_list.NumSpriteSheets() + other_sheet.spritesheet_list.NumSpriteSheets(),
  86. spritesheet_list.NumSprites() + other_sheet.spritesheet_list.NumSprites()
  87. );
  88. new_sheet->spritesheet_list = other_sheet.spritesheet_list;
  89. new_sheet->spritesheet_list.Merge(spritesheet_list);
  90. new_sheet->specificity_offset = specificity_offset + other_sheet.specificity_offset;
  91. return new_sheet;
  92. }
  93. // Builds the node index for a combined style sheet.
  94. void StyleSheet::BuildNodeIndexAndOptimizeProperties()
  95. {
  96. if (complete_node_index.empty())
  97. {
  98. styled_node_index.clear();
  99. complete_node_index.clear();
  100. root->BuildIndexAndOptimizeProperties(styled_node_index, complete_node_index, *this);
  101. root->SetStructurallyVolatileRecursive(false);
  102. }
  103. }
  104. // Returns the Keyframes of the given name, or null if it does not exist.
  105. Keyframes * StyleSheet::GetKeyframes(const String & name)
  106. {
  107. auto it = keyframes.find(name);
  108. if (it != keyframes.end())
  109. return &(it->second);
  110. return nullptr;
  111. }
  112. SharedPtr<Decorator> StyleSheet::GetDecorator(const String& name) const
  113. {
  114. auto it = decorator_map.find(name);
  115. if (it == decorator_map.end())
  116. return nullptr;
  117. return it->second.decorator;
  118. }
  119. const Sprite* StyleSheet::GetSprite(const String& name) const
  120. {
  121. return spritesheet_list.GetSprite(name);
  122. }
  123. DecoratorList StyleSheet::InstanceDecoratorsFromString(const String& decorator_string_value, const PropertySource* source) const
  124. {
  125. // Decorators are declared as
  126. // decorator: <decorator-value>[, <decorator-value> ...];
  127. // Where <decorator-value> is either a @decorator name:
  128. // decorator: invader-theme-background, ...;
  129. // or is an anonymous decorator with inline properties
  130. // decorator: tiled-box( <shorthand properties> ), ...;
  131. DecoratorList decorator_list;
  132. if (decorator_string_value.empty() || decorator_string_value == NONE)
  133. return decorator_list;
  134. const char* source_name = (source ? source->path.c_str() : "");
  135. const int source_line_number = (source ? source->line_number : 0);
  136. // Make sure we don't split inside the parenthesis since they may appear in decorator shorthands.
  137. StringList decorator_string_list;
  138. StringUtilities::ExpandString(decorator_string_list, decorator_string_value, ',', '(', ')');
  139. decorator_list.reserve(decorator_string_list.size());
  140. // Get or instance each decorator in the comma-separated string list
  141. for (const String& decorator_string : decorator_string_list)
  142. {
  143. const size_t shorthand_open = decorator_string.find('(');
  144. const size_t shorthand_close = decorator_string.rfind(')');
  145. const bool invalid_parenthesis = (shorthand_open == String::npos || shorthand_close == String::npos || shorthand_open >= shorthand_close);
  146. if (invalid_parenthesis)
  147. {
  148. // We found no parenthesis, that means the value must be a name of a @decorator rule, look it up
  149. SharedPtr<Decorator> decorator = GetDecorator(decorator_string);
  150. if (decorator)
  151. decorator_list.emplace_back(std::move(decorator));
  152. else
  153. 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_name, source_line_number);
  154. }
  155. else
  156. {
  157. // Since we have parentheses it must be an anonymous decorator with inline properties
  158. const String type = StringUtilities::StripWhitespace(decorator_string.substr(0, shorthand_open));
  159. // Check for valid decorator type
  160. DecoratorInstancer* instancer = Factory::GetDecoratorInstancer(type);
  161. if (!instancer)
  162. {
  163. Log::Message(Log::LT_WARNING, "Decorator type '%s' not found, declared at %s:%d", type.c_str(), source ? source->path.c_str() : "", source ? source->line_number : -1);
  164. continue;
  165. }
  166. const String shorthand = decorator_string.substr(shorthand_open + 1, shorthand_close - shorthand_open - 1);
  167. const PropertySpecification& specification = instancer->GetPropertySpecification();
  168. // Parse the shorthand properties given by the 'decorator' shorthand property
  169. PropertyDictionary properties;
  170. if (!specification.ParsePropertyDeclaration(properties, "decorator", shorthand))
  171. {
  172. Log::Message(Log::LT_WARNING, "Could not parse decorator value '%s' at %s:%d", decorator_string.c_str(), source_name, source_line_number);
  173. continue;
  174. }
  175. // Set unspecified values to their defaults
  176. specification.SetPropertyDefaults(properties);
  177. SharedPtr<Decorator> decorator = instancer->InstanceDecorator(type, properties, DecoratorInstancerInterface(*this));
  178. if (decorator)
  179. decorator_list.emplace_back(std::move(decorator));
  180. else
  181. {
  182. Log::Message(Log::LT_WARNING, "Decorator '%s' could not be instanced, declared at %s:%d", decorator_string.c_str(), source_name, source_line_number);
  183. continue;
  184. }
  185. }
  186. }
  187. return decorator_list;
  188. }
  189. FontEffectListPtr StyleSheet::InstanceFontEffectsFromString(const String& font_effect_string_value, const PropertySource* source) const
  190. {
  191. // Font-effects are declared as
  192. // font-effect: <font-effect-value>[, <font-effect-value> ...];
  193. // Where <font-effect-value> is declared with inline properties, e.g.
  194. // font-effect: outline( 1px black ), ...;
  195. if (font_effect_string_value.empty() || font_effect_string_value == NONE)
  196. return nullptr;
  197. const char* source_name = (source ? source->path.c_str() : "");
  198. const int source_line_number = (source ? source->line_number : 0);
  199. FontEffectList font_effect_list;
  200. // Make sure we don't split inside the parenthesis since they may appear in decorator shorthands.
  201. StringList font_effect_string_list;
  202. StringUtilities::ExpandString(font_effect_string_list, font_effect_string_value, ',', '(', ')');
  203. font_effect_list.reserve(font_effect_string_list.size());
  204. // Get or instance each decorator in the comma-separated string list
  205. for (const String& font_effect_string : font_effect_string_list)
  206. {
  207. const size_t shorthand_open = font_effect_string.find('(');
  208. const size_t shorthand_close = font_effect_string.rfind(')');
  209. const bool invalid_parenthesis = (shorthand_open == String::npos || shorthand_close == String::npos || shorthand_open >= shorthand_close);
  210. if (invalid_parenthesis)
  211. {
  212. // We found no parenthesis, font-effects can only be declared anonymously for now.
  213. Log::Message(Log::LT_WARNING, "Invalid syntax for font-effect '%s', declared at %s:%d", font_effect_string.c_str(), source_name, source_line_number);
  214. }
  215. else
  216. {
  217. // Since we have parentheses it must be an anonymous decorator with inline properties
  218. const String type = StringUtilities::StripWhitespace(font_effect_string.substr(0, shorthand_open));
  219. // Check for valid font-effect type
  220. FontEffectInstancer* instancer = Factory::GetFontEffectInstancer(type);
  221. if (!instancer)
  222. {
  223. Log::Message(Log::LT_WARNING, "Font-effect type '%s' not found, declared at %s:%d", type.c_str(), source_name, source_line_number);
  224. continue;
  225. }
  226. const String shorthand = font_effect_string.substr(shorthand_open + 1, shorthand_close - shorthand_open - 1);
  227. const PropertySpecification& specification = instancer->GetPropertySpecification();
  228. // Parse the shorthand properties given by the 'font-effect' shorthand property
  229. PropertyDictionary properties;
  230. if (!specification.ParsePropertyDeclaration(properties, "font-effect", shorthand))
  231. {
  232. Log::Message(Log::LT_WARNING, "Could not parse decorator value '%s' at %s:%d", font_effect_string.c_str(), source_name, source_line_number);
  233. continue;
  234. }
  235. // Set unspecified values to their defaults
  236. specification.SetPropertyDefaults(properties);
  237. SharedPtr<FontEffect> font_effect = instancer->InstanceFontEffect(type, properties);
  238. if (font_effect)
  239. {
  240. // Create a unique hash value for the given type and values
  241. size_t fingerprint = std::hash<String>{}(type);
  242. for (const auto& id_value : properties.GetProperties())
  243. Utilities::HashCombine(fingerprint, id_value.second.Get<String>());
  244. font_effect->SetFingerprint(fingerprint);
  245. font_effect_list.emplace_back(std::move(font_effect));
  246. }
  247. else
  248. {
  249. Log::Message(Log::LT_WARNING, "Font-effect '%s' could not be instanced, declared at %s:%d", font_effect_string.c_str(), source_name, source_line_number);
  250. continue;
  251. }
  252. }
  253. }
  254. // Partition the list such that the back layer effects appear before the front layer effects
  255. std::stable_partition(font_effect_list.begin(), font_effect_list.end(),
  256. [](const SharedPtr<const FontEffect>& effect) { return effect->GetLayer() == FontEffect::Layer::Back; }
  257. );
  258. return std::make_shared<FontEffectList>(std::move(font_effect_list));
  259. }
  260. // Returns the compiled element definition for a given element hierarchy.
  261. SharedPtr<ElementDefinition> StyleSheet::GetElementDefinition(const Element* element) const
  262. {
  263. RMLUI_ASSERT_NONRECURSIVE;
  264. // See if there are any styles defined for this element.
  265. // Using static to avoid allocations. Make sure we don't call this function recursively.
  266. static std::vector< const StyleSheetNode* > applicable_nodes;
  267. applicable_nodes.clear();
  268. String tags[] = {element->GetTagName(), ""};
  269. for (int i = 0; i < 2; i++)
  270. {
  271. auto it_nodes = styled_node_index.find(tags[i]);
  272. if (it_nodes != styled_node_index.end())
  273. {
  274. const NodeList& nodes = it_nodes->second;
  275. // There are! Now see if we satisfy all of their parenting requirements. What this involves is traversing the style
  276. // nodes backwards, trying to match nodes in the element's hierarchy to nodes in the style hierarchy.
  277. for (StyleSheetNode* node : nodes)
  278. {
  279. if (node->IsApplicable(element))
  280. {
  281. // Get the node to add any of its non-tag children that we match into our list.
  282. node->GetApplicableDescendants(applicable_nodes, element);
  283. }
  284. }
  285. }
  286. }
  287. std::sort(applicable_nodes.begin(), applicable_nodes.end(), StyleSheetNodeSort);
  288. // If this element definition won't actually store any information, don't bother with it.
  289. if (applicable_nodes.empty())
  290. return nullptr;
  291. // Check if this puppy has already been cached in the node index; it may be that it has already been created by an
  292. // element with a different address but an identical output definition.
  293. size_t seed = 0;
  294. for (const StyleSheetNode* node : applicable_nodes)
  295. Utilities::HashCombine(seed, node);
  296. auto cache_iterator = node_cache.find(seed);
  297. if (cache_iterator != node_cache.end())
  298. {
  299. SharedPtr<ElementDefinition>& definition = (*cache_iterator).second;
  300. return definition;
  301. }
  302. // Create the new definition and add it to our cache.
  303. auto new_definition = std::make_shared<ElementDefinition>(applicable_nodes);
  304. // Add to the node cache.
  305. node_cache[seed] = new_definition;
  306. return new_definition;
  307. }
  308. }
  309. }