StyleSheet.cpp 15 KB

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