StyleSheetParser.cpp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  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 "StyleSheetParser.h"
  29. #include "ComputeProperty.h"
  30. #include "StyleSheetFactory.h"
  31. #include "StyleSheetNode.h"
  32. #include "../../Include/RmlUi/Core/DecoratorInstancer.h"
  33. #include "../../Include/RmlUi/Core/Factory.h"
  34. #include "../../Include/RmlUi/Core/Log.h"
  35. #include "../../Include/RmlUi/Core/Profiling.h"
  36. #include "../../Include/RmlUi/Core/PropertyDefinition.h"
  37. #include "../../Include/RmlUi/Core/PropertySpecification.h"
  38. #include "../../Include/RmlUi/Core/StreamMemory.h"
  39. #include "../../Include/RmlUi/Core/StyleSheet.h"
  40. #include "../../Include/RmlUi/Core/StyleSheetContainer.h"
  41. #include "../../Include/RmlUi/Core/StyleSheetSpecification.h"
  42. #include <algorithm>
  43. #include <string.h>
  44. namespace Rml {
  45. class AbstractPropertyParser {
  46. public:
  47. virtual bool Parse(const String& name, const String& value) = 0;
  48. };
  49. /*
  50. * PropertySpecificationParser just passes the parsing to a property specification. Usually
  51. * the main stylesheet specification, except for e.g. @decorator blocks.
  52. */
  53. class PropertySpecificationParser final : public AbstractPropertyParser {
  54. private:
  55. // The dictionary to store the properties in.
  56. PropertyDictionary& properties;
  57. // The specification used to parse the values. Normally the default stylesheet specification, but not for e.g. all at-rules such as decorators.
  58. const PropertySpecification& specification;
  59. public:
  60. PropertySpecificationParser(PropertyDictionary& properties, const PropertySpecification& specification) : properties(properties), specification(specification) {}
  61. bool Parse(const String& name, const String& value) override
  62. {
  63. return specification.ParsePropertyDeclaration(properties, name, value);
  64. }
  65. };
  66. /*
  67. * Spritesheets need a special parser because its property names are arbitrary keys,
  68. * while its values are always rectangles. Thus, it must be parsed with a special "rectangle" parser
  69. * for every name-value pair. We can probably optimize this for @performance.
  70. */
  71. class SpritesheetPropertyParser final : public AbstractPropertyParser {
  72. private:
  73. String image_source;
  74. SpriteDefinitionList sprite_definitions;
  75. PropertyDictionary properties;
  76. PropertySpecification specification;
  77. PropertyId id_rx, id_ry, id_rw, id_rh;
  78. ShorthandId id_rectangle;
  79. public:
  80. SpritesheetPropertyParser() : specification(4, 1)
  81. {
  82. id_rx = specification.RegisterProperty("rectangle-x", "", false, false).AddParser("length").GetId();
  83. id_ry = specification.RegisterProperty("rectangle-y", "", false, false).AddParser("length").GetId();
  84. id_rw = specification.RegisterProperty("rectangle-w", "", false, false).AddParser("length").GetId();
  85. id_rh = specification.RegisterProperty("rectangle-h", "", false, false).AddParser("length").GetId();
  86. id_rectangle = specification.RegisterShorthand("rectangle", "rectangle-x, rectangle-y, rectangle-w, rectangle-h", ShorthandType::FallThrough);
  87. }
  88. const String& GetImageSource() const
  89. {
  90. return image_source;
  91. }
  92. const SpriteDefinitionList& GetSpriteDefinitions() const
  93. {
  94. return sprite_definitions;
  95. }
  96. void Clear() {
  97. image_source.clear();
  98. sprite_definitions.clear();
  99. }
  100. bool Parse(const String& name, const String& value) override
  101. {
  102. if (name == "src")
  103. {
  104. image_source = value;
  105. }
  106. else
  107. {
  108. if (!specification.ParseShorthandDeclaration(properties, id_rectangle, value))
  109. return false;
  110. Rectangle rectangle;
  111. if (auto property = properties.GetProperty(id_rx))
  112. rectangle.x = ComputeAbsoluteLength(*property, 1.f, Vector2f(1.f));
  113. if (auto property = properties.GetProperty(id_ry))
  114. rectangle.y = ComputeAbsoluteLength(*property, 1.f, Vector2f(1.f));
  115. if (auto property = properties.GetProperty(id_rw))
  116. rectangle.width = ComputeAbsoluteLength(*property, 1.f, Vector2f(1.f));
  117. if (auto property = properties.GetProperty(id_rh))
  118. rectangle.height = ComputeAbsoluteLength(*property, 1.f, Vector2f(1.f));
  119. sprite_definitions.emplace_back(name, rectangle);
  120. }
  121. return true;
  122. }
  123. };
  124. static UniquePtr<SpritesheetPropertyParser> spritesheet_property_parser;
  125. /*
  126. * Media queries need a special parser because they have unique properties that
  127. * aren't admissible in other property declaration contexts and the syntax of
  128. */
  129. class MediaQueryPropertyParser final : public AbstractPropertyParser {
  130. private:
  131. // The dictionary to store the properties in.
  132. PropertyDictionary* properties;
  133. PropertySpecification specification;
  134. public:
  135. MediaQueryPropertyParser() : specification(14, 0)
  136. {
  137. specification.RegisterProperty("width", "", false, false, CastId(MediaQueryId::Width)).AddParser("length");
  138. specification.RegisterProperty("min-width", "", false, false, CastId(MediaQueryId::MinWidth)).AddParser("length");
  139. specification.RegisterProperty("max-width", "", false, false, CastId(MediaQueryId::MaxWidth)).AddParser("length");
  140. specification.RegisterProperty("height", "", false, false, CastId(MediaQueryId::Height)).AddParser("length");
  141. specification.RegisterProperty("min-height", "", false, false, CastId(MediaQueryId::MinHeight)).AddParser("length");
  142. specification.RegisterProperty("max-height", "", false, false, CastId(MediaQueryId::MaxHeight)).AddParser("length");
  143. specification.RegisterProperty("aspect-ratio", "", false, false, CastId(MediaQueryId::AspectRatio)).AddParser("ratio");
  144. specification.RegisterProperty("min-aspect-ratio", "", false, false, CastId(MediaQueryId::MinAspectRatio)).AddParser("ratio");
  145. specification.RegisterProperty("max-aspect-ratio", "", false, false, CastId(MediaQueryId::MaxAspectRatio)).AddParser("ratio");
  146. specification.RegisterProperty("resolution", "", false, false, CastId(MediaQueryId::Resolution)).AddParser("resolution");
  147. specification.RegisterProperty("min-resolution", "", false, false, CastId(MediaQueryId::MinResolution)).AddParser("resolution");
  148. specification.RegisterProperty("max-resolution", "", false, false, CastId(MediaQueryId::MaxResolution)).AddParser("resolution");
  149. specification.RegisterProperty("orientation", "", false, false, CastId(MediaQueryId::Orientation)).AddParser("keyword", "landscape, portrait");
  150. }
  151. void SetTargetProperties(PropertyDictionary* _properties)
  152. {
  153. properties = _properties;
  154. }
  155. void Clear() {
  156. properties = nullptr;
  157. }
  158. bool Parse(const String& name, const String& value) override
  159. {
  160. RMLUI_ASSERT(properties);
  161. return specification.ParsePropertyDeclaration(*properties, name, value);
  162. }
  163. };
  164. static UniquePtr<MediaQueryPropertyParser> media_query_property_parser;
  165. StyleSheetParser::StyleSheetParser()
  166. {
  167. line_number = 0;
  168. stream = nullptr;
  169. parse_buffer_pos = 0;
  170. }
  171. StyleSheetParser::~StyleSheetParser()
  172. {
  173. }
  174. void StyleSheetParser::Initialise()
  175. {
  176. spritesheet_property_parser = MakeUnique<SpritesheetPropertyParser>();
  177. media_query_property_parser = MakeUnique<MediaQueryPropertyParser>();
  178. }
  179. void StyleSheetParser::Shutdown()
  180. {
  181. spritesheet_property_parser.reset();
  182. media_query_property_parser.reset();
  183. }
  184. static bool IsValidIdentifier(const String& str)
  185. {
  186. if (str.empty())
  187. return false;
  188. for (size_t i = 0; i < str.size(); i++)
  189. {
  190. char c = str[i];
  191. bool valid = (
  192. (c >= 'a' && c <= 'z')
  193. || (c >= 'A' && c <= 'Z')
  194. || (c >= '0' && c <= '9')
  195. || (c == '-')
  196. || (c == '_')
  197. );
  198. if (!valid)
  199. return false;
  200. }
  201. return true;
  202. }
  203. static void PostprocessKeyframes(KeyframesMap& keyframes_map)
  204. {
  205. for (auto& keyframes_pair : keyframes_map)
  206. {
  207. Keyframes& keyframes = keyframes_pair.second;
  208. auto& blocks = keyframes.blocks;
  209. auto& property_ids = keyframes.property_ids;
  210. // Sort keyframes on selector value.
  211. std::sort(blocks.begin(), blocks.end(), [](const KeyframeBlock& a, const KeyframeBlock& b) { return a.normalized_time < b.normalized_time; });
  212. // Add all property names specified by any block
  213. if(blocks.size() > 0) property_ids.reserve(blocks.size() * blocks[0].properties.GetNumProperties());
  214. for(auto& block : blocks)
  215. {
  216. for (auto& property : block.properties.GetProperties())
  217. property_ids.push_back(property.first);
  218. }
  219. // Remove duplicate property names
  220. std::sort(property_ids.begin(), property_ids.end());
  221. property_ids.erase(std::unique(property_ids.begin(), property_ids.end()), property_ids.end());
  222. property_ids.shrink_to_fit();
  223. }
  224. }
  225. bool StyleSheetParser::ParseKeyframeBlock(KeyframesMap& keyframes_map, const String& identifier, const String& rules, const PropertyDictionary& properties)
  226. {
  227. if (!IsValidIdentifier(identifier))
  228. {
  229. Log::Message(Log::LT_WARNING, "Invalid keyframes identifier '%s' at %s:%d", identifier.c_str(), stream_file_name.c_str(), line_number);
  230. return false;
  231. }
  232. if (properties.GetNumProperties() == 0)
  233. return true;
  234. StringList rule_list;
  235. StringUtilities::ExpandString(rule_list, rules);
  236. Vector<float> rule_values;
  237. rule_values.reserve(rule_list.size());
  238. for (auto rule : rule_list)
  239. {
  240. float value = 0.0f;
  241. int count = 0;
  242. rule = StringUtilities::ToLower(rule);
  243. if (rule == "from")
  244. rule_values.push_back(0.0f);
  245. else if (rule == "to")
  246. rule_values.push_back(1.0f);
  247. else if(sscanf(rule.c_str(), "%f%%%n", &value, &count) == 1)
  248. if(count > 0 && value >= 0.0f && value <= 100.0f)
  249. rule_values.push_back(0.01f * value);
  250. }
  251. if (rule_values.empty())
  252. {
  253. Log::Message(Log::LT_WARNING, "Invalid keyframes rule(s) '%s' at %s:%d", rules.c_str(), stream_file_name.c_str(), line_number);
  254. return false;
  255. }
  256. Keyframes& keyframes = keyframes_map[identifier];
  257. for(float selector : rule_values)
  258. {
  259. auto it = std::find_if(keyframes.blocks.begin(), keyframes.blocks.end(), [selector](const KeyframeBlock& keyframe_block) { return Math::AbsoluteValue(keyframe_block.normalized_time - selector) < 0.0001f; });
  260. if (it == keyframes.blocks.end())
  261. {
  262. keyframes.blocks.emplace_back(selector);
  263. it = (keyframes.blocks.end() - 1);
  264. }
  265. else
  266. {
  267. // In case of duplicate keyframes, we only use the latest definition as per CSS rules
  268. it->properties = PropertyDictionary();
  269. }
  270. it->properties.Import(properties);
  271. }
  272. return true;
  273. }
  274. bool StyleSheetParser::ParseDecoratorBlock(const String& at_name, DecoratorSpecificationMap& decorator_map, const StyleSheet& style_sheet, const SharedPtr<const PropertySource>& source)
  275. {
  276. StringList name_type;
  277. StringUtilities::ExpandString(name_type, at_name, ':');
  278. if (name_type.size() != 2 || name_type[0].empty() || name_type[1].empty())
  279. {
  280. Log::Message(Log::LT_WARNING, "Decorator syntax error at %s:%d. Use syntax: '@decorator name : type { ... }'.", stream_file_name.c_str(), line_number);
  281. return false;
  282. }
  283. const String& name = name_type[0];
  284. String decorator_type = name_type[1];
  285. auto it_find = decorator_map.find(name);
  286. if (it_find != decorator_map.end())
  287. {
  288. Log::Message(Log::LT_WARNING, "Decorator with name '%s' already declared, ignoring decorator at %s:%d.", name.c_str(), stream_file_name.c_str(), line_number);
  289. return false;
  290. }
  291. // Get the instancer associated with the decorator type
  292. DecoratorInstancer* decorator_instancer = Factory::GetDecoratorInstancer(decorator_type);
  293. PropertyDictionary properties;
  294. if(!decorator_instancer)
  295. {
  296. // Type is not a declared decorator type, instead, see if it is another decorator name, then we inherit its properties.
  297. auto it = decorator_map.find(decorator_type);
  298. if (it != decorator_map.end())
  299. {
  300. // Yes, try to retrieve the instancer from the parent type, and add its property values.
  301. decorator_instancer = Factory::GetDecoratorInstancer(it->second.decorator_type);
  302. properties = it->second.properties;
  303. decorator_type = it->second.decorator_type;
  304. }
  305. // If we still don't have an instancer, we cannot continue.
  306. if (!decorator_instancer)
  307. {
  308. Log::Message(Log::LT_WARNING, "Invalid decorator type '%s' declared at %s:%d.", decorator_type.c_str(), stream_file_name.c_str(), line_number);
  309. return false;
  310. }
  311. }
  312. const PropertySpecification& property_specification = decorator_instancer->GetPropertySpecification();
  313. PropertySpecificationParser parser(properties, property_specification);
  314. if (!ReadProperties(parser))
  315. return false;
  316. // Set non-defined properties to their defaults
  317. property_specification.SetPropertyDefaults(properties);
  318. properties.SetSourceOfAllProperties(source);
  319. SharedPtr<Decorator> decorator = decorator_instancer->InstanceDecorator(decorator_type, properties, DecoratorInstancerInterface(style_sheet));
  320. if (!decorator)
  321. {
  322. Log::Message(Log::LT_WARNING, "Could not instance decorator of type '%s' declared at %s:%d.", decorator_type.c_str(), stream_file_name.c_str(), line_number);
  323. return false;
  324. }
  325. decorator_map.emplace(name, DecoratorSpecification{ std::move(decorator_type), std::move(properties), std::move(decorator) });
  326. return true;
  327. }
  328. bool StyleSheetParser::ParseMediaFeatureMap(PropertyDictionary& properties, const String & rules)
  329. {
  330. media_query_property_parser->SetTargetProperties(&properties);
  331. enum ParseState { Global, Name, Value };
  332. ParseState state = Name;
  333. char character = 0;
  334. size_t cursor = 0;
  335. String name;
  336. String current_string;
  337. while(cursor++ < rules.length())
  338. {
  339. character = rules[cursor];
  340. switch(character)
  341. {
  342. case '(':
  343. {
  344. if (state != Global)
  345. {
  346. Log::Message(Log::LT_WARNING, "Unexpected '(' in @media query list at %s:%d.", stream_file_name.c_str(), line_number);
  347. return false;
  348. }
  349. current_string = StringUtilities::StripWhitespace(StringUtilities::ToLower(current_string));
  350. if (current_string != "and")
  351. {
  352. Log::Message(Log::LT_WARNING, "Unexpected '%s' in @media query list at %s:%d. Expected 'and'.", current_string.c_str(), stream_file_name.c_str(), line_number);
  353. return false;
  354. }
  355. current_string.clear();
  356. state = Name;
  357. }
  358. break;
  359. case ')':
  360. {
  361. if (state != Value)
  362. {
  363. Log::Message(Log::LT_WARNING, "Unexpected ')' in @media query list at %s:%d.", stream_file_name.c_str(), line_number);
  364. return false;
  365. }
  366. current_string = StringUtilities::StripWhitespace(current_string);
  367. if(!media_query_property_parser->Parse(name, current_string))
  368. Log::Message(Log::LT_WARNING, "Syntax error parsing media-query property declaration '%s: %s;' in %s: %d.", name.c_str(), current_string.c_str(), stream_file_name.c_str(), line_number);
  369. current_string.clear();
  370. state = Global;
  371. }
  372. break;
  373. case ':':
  374. {
  375. if (state != Name)
  376. {
  377. Log::Message(Log::LT_WARNING, "Unexpected ':' in @media query list at %s:%d.", stream_file_name.c_str(), line_number);
  378. return false;
  379. }
  380. current_string = StringUtilities::StripWhitespace(StringUtilities::ToLower(current_string));
  381. if (!IsValidIdentifier(current_string))
  382. {
  383. Log::Message(Log::LT_WARNING, "Malformed property name '%s' in @media query list at %s:%d.", current_string.c_str(), stream_file_name.c_str(), line_number);
  384. return false;
  385. }
  386. name = current_string;
  387. current_string.clear();
  388. state = Value;
  389. }
  390. break;
  391. default:
  392. current_string += character;
  393. }
  394. }
  395. if (properties.GetNumProperties() == 0)
  396. {
  397. Log::Message(Log::LT_WARNING, "Media query list parsing yielded no properties at %s:%d.", stream_file_name.c_str(), line_number);
  398. }
  399. return true;
  400. }
  401. int StyleSheetParser::Parse(MediaBlockList& style_sheets, Stream* _stream, int begin_line_number)
  402. {
  403. RMLUI_ZoneScoped;
  404. int rule_count = 0;
  405. line_number = begin_line_number;
  406. stream = _stream;
  407. stream_file_name = StringUtilities::Replace(stream->GetSourceURL().GetURL(), '|', ':');
  408. enum class State { Global, AtRuleIdentifier, KeyframeBlock, Invalid };
  409. State state = State::Global;
  410. MediaBlock current_block = {};
  411. // Need to track whether currently inside a nested media block or not, since the default scope is also a media block
  412. bool inside_media_block = false;
  413. // At-rules given by the following syntax in global space: @identifier name { block }
  414. String at_rule_name;
  415. // Look for more styles while data is available
  416. while (FillBuffer())
  417. {
  418. String pre_token_str;
  419. while (char token = FindToken(pre_token_str, "{@}", true))
  420. {
  421. switch (state)
  422. {
  423. case State::Global:
  424. {
  425. if (token == '{')
  426. {
  427. // Initialize current block if not present
  428. if (!current_block.stylesheet)
  429. {
  430. current_block = MediaBlock{PropertyDictionary{}, UniquePtr<StyleSheet>(new StyleSheet())};
  431. }
  432. const int rule_line_number = (int)line_number;
  433. // Read the attributes
  434. PropertyDictionary properties;
  435. PropertySpecificationParser parser(properties, StyleSheetSpecification::GetPropertySpecification());
  436. if (!ReadProperties(parser))
  437. continue;
  438. StringList rule_name_list;
  439. StringUtilities::ExpandString(rule_name_list, pre_token_str);
  440. // Add style nodes to the root of the tree
  441. for (size_t i = 0; i < rule_name_list.size(); i++)
  442. {
  443. auto source = MakeShared<PropertySource>(stream_file_name, rule_line_number, rule_name_list[i]);
  444. properties.SetSourceOfAllProperties(source);
  445. ImportProperties(current_block.stylesheet->root.get(), rule_name_list[i], properties, rule_count);
  446. }
  447. rule_count++;
  448. }
  449. else if (token == '@')
  450. {
  451. state = State::AtRuleIdentifier;
  452. }
  453. else if (inside_media_block && token == '}')
  454. {
  455. // Complete current block
  456. PostprocessKeyframes(current_block.stylesheet->keyframes);
  457. current_block.stylesheet->specificity_offset = rule_count;
  458. style_sheets.push_back(std::move(current_block));
  459. current_block = {};
  460. inside_media_block = false;
  461. break;
  462. }
  463. else
  464. {
  465. Log::Message(Log::LT_WARNING, "Invalid character '%c' found while parsing stylesheet at %s:%d. Trying to proceed.", token, stream_file_name.c_str(), line_number);
  466. }
  467. }
  468. break;
  469. case State::AtRuleIdentifier:
  470. {
  471. if (token == '{')
  472. {
  473. // Initialize current block if not present
  474. if (!current_block.stylesheet)
  475. {
  476. current_block = {PropertyDictionary{}, UniquePtr<StyleSheet>(new StyleSheet())};
  477. }
  478. String at_rule_identifier = pre_token_str.substr(0, pre_token_str.find(' '));
  479. at_rule_name = StringUtilities::StripWhitespace(pre_token_str.substr(at_rule_identifier.size()));
  480. if (at_rule_identifier == "keyframes")
  481. {
  482. state = State::KeyframeBlock;
  483. }
  484. else if (at_rule_identifier == "decorator")
  485. {
  486. auto source = MakeShared<PropertySource>(stream_file_name, (int)line_number, pre_token_str);
  487. ParseDecoratorBlock(at_rule_name, current_block.stylesheet->decorator_map, *current_block.stylesheet, source);
  488. at_rule_name.clear();
  489. state = State::Global;
  490. }
  491. else if (at_rule_identifier == "spritesheet")
  492. {
  493. // The spritesheet parser is reasonably heavy to initialize, so we make it a static global.
  494. ReadProperties(*spritesheet_property_parser);
  495. const String& image_source = spritesheet_property_parser->GetImageSource();
  496. const SpriteDefinitionList& sprite_definitions = spritesheet_property_parser->GetSpriteDefinitions();
  497. if (at_rule_name.empty())
  498. {
  499. Log::Message(Log::LT_WARNING, "No name given for @spritesheet at %s:%d", stream_file_name.c_str(), line_number);
  500. }
  501. else if (sprite_definitions.empty())
  502. {
  503. Log::Message(Log::LT_WARNING, "Spritesheet with name '%s' has no sprites defined, ignored. At %s:%d", at_rule_name.c_str(), stream_file_name.c_str(), line_number);
  504. }
  505. else if (image_source.empty())
  506. {
  507. Log::Message(Log::LT_WARNING, "No image source (property 'src') specified for spritesheet '%s'. At %s:%d", at_rule_name.c_str(), stream_file_name.c_str(), line_number);
  508. }
  509. else
  510. {
  511. current_block.stylesheet->spritesheet_list.AddSpriteSheet(at_rule_name, image_source, stream_file_name, (int)line_number, sprite_definitions);
  512. }
  513. spritesheet_property_parser->Clear();
  514. at_rule_name.clear();
  515. state = State::Global;
  516. }
  517. else if (at_rule_identifier == "media")
  518. {
  519. // complete the current "global" block if present and start a new block
  520. if (current_block.stylesheet)
  521. {
  522. PostprocessKeyframes(current_block.stylesheet->keyframes);
  523. current_block.stylesheet->specificity_offset = rule_count;
  524. style_sheets.push_back(std::move(current_block));
  525. current_block = {};
  526. }
  527. // parse media query list into block
  528. PropertyDictionary feature_map;
  529. ParseMediaFeatureMap(feature_map, at_rule_name);
  530. current_block = {std::move(feature_map), UniquePtr<StyleSheet>(new StyleSheet())};
  531. inside_media_block = true;
  532. state = State::Global;
  533. }
  534. else
  535. {
  536. // Invalid identifier, should ignore
  537. at_rule_name.clear();
  538. state = State::Global;
  539. Log::Message(Log::LT_WARNING, "Invalid at-rule identifier '%s' found in stylesheet at %s:%d", at_rule_identifier.c_str(), stream_file_name.c_str(), line_number);
  540. }
  541. }
  542. else
  543. {
  544. Log::Message(Log::LT_WARNING, "Invalid character '%c' found while parsing at-rule identifier in stylesheet at %s:%d", token, stream_file_name.c_str(), line_number);
  545. state = State::Invalid;
  546. }
  547. }
  548. break;
  549. case State::KeyframeBlock:
  550. {
  551. if (token == '{')
  552. {
  553. // Initialize current block if not present
  554. if (!current_block.stylesheet)
  555. {
  556. current_block = {PropertyDictionary{}, UniquePtr<StyleSheet>(new StyleSheet())};
  557. }
  558. // Each keyframe in keyframes has its own block which is processed here
  559. PropertyDictionary properties;
  560. PropertySpecificationParser parser(properties, StyleSheetSpecification::GetPropertySpecification());
  561. if(!ReadProperties(parser))
  562. continue;
  563. if (!ParseKeyframeBlock(current_block.stylesheet->keyframes, at_rule_name, pre_token_str, properties))
  564. continue;
  565. }
  566. else if (token == '}')
  567. {
  568. at_rule_name.clear();
  569. state = State::Global;
  570. }
  571. else
  572. {
  573. Log::Message(Log::LT_WARNING, "Invalid character '%c' found while parsing keyframe block in stylesheet at %s:%d", token, stream_file_name.c_str(), line_number);
  574. state = State::Invalid;
  575. }
  576. }
  577. break;
  578. default:
  579. RMLUI_ERROR;
  580. state = State::Invalid;
  581. break;
  582. }
  583. if (state == State::Invalid)
  584. break;
  585. }
  586. if (state == State::Invalid)
  587. break;
  588. }
  589. // Complete last block if present
  590. if (current_block.stylesheet)
  591. {
  592. PostprocessKeyframes(current_block.stylesheet->keyframes);
  593. current_block.stylesheet->specificity_offset = rule_count;
  594. style_sheets.push_back(std::move(current_block));
  595. }
  596. return rule_count;
  597. }
  598. bool StyleSheetParser::ParseProperties(PropertyDictionary& parsed_properties, const String& properties)
  599. {
  600. RMLUI_ASSERT(!stream);
  601. StreamMemory stream_owner((const byte*)properties.c_str(), properties.size());
  602. stream = &stream_owner;
  603. PropertySpecificationParser parser(parsed_properties, StyleSheetSpecification::GetPropertySpecification());
  604. bool success = ReadProperties(parser);
  605. stream = nullptr;
  606. return success;
  607. }
  608. StyleSheetNodeListRaw StyleSheetParser::ConstructNodes(StyleSheetNode& root_node, const String& selectors)
  609. {
  610. const PropertyDictionary empty_properties;
  611. StringList selector_list;
  612. StringUtilities::ExpandString(selector_list, selectors);
  613. StyleSheetNodeListRaw leaf_nodes;
  614. for (const String& selector : selector_list)
  615. {
  616. StyleSheetNode* leaf_node = ImportProperties(&root_node, selector, empty_properties, 0);
  617. if (leaf_node != &root_node)
  618. leaf_nodes.push_back(leaf_node);
  619. }
  620. return leaf_nodes;
  621. }
  622. bool StyleSheetParser::ReadProperties(AbstractPropertyParser& property_parser)
  623. {
  624. RMLUI_ZoneScoped;
  625. String name;
  626. String value;
  627. enum ParseState { NAME, VALUE, QUOTE };
  628. ParseState state = NAME;
  629. char character;
  630. char previous_character = 0;
  631. while (ReadCharacter(character))
  632. {
  633. parse_buffer_pos++;
  634. switch (state)
  635. {
  636. case NAME:
  637. {
  638. if (character == ';')
  639. {
  640. name = StringUtilities::StripWhitespace(name);
  641. if (!name.empty())
  642. {
  643. Log::Message(Log::LT_WARNING, "Found name with no value while parsing property declaration '%s' at %s:%d", name.c_str(), stream_file_name.c_str(), line_number);
  644. name.clear();
  645. }
  646. }
  647. else if (character == '}')
  648. {
  649. name = StringUtilities::StripWhitespace(name);
  650. if (!name.empty())
  651. Log::Message(Log::LT_WARNING, "End of rule encountered while parsing property declaration '%s' at %s:%d", name.c_str(), stream_file_name.c_str(), line_number);
  652. return true;
  653. }
  654. else if (character == ':')
  655. {
  656. name = StringUtilities::StripWhitespace(name);
  657. state = VALUE;
  658. }
  659. else
  660. name += character;
  661. }
  662. break;
  663. case VALUE:
  664. {
  665. if (character == ';')
  666. {
  667. value = StringUtilities::StripWhitespace(value);
  668. if (!property_parser.Parse(name, value))
  669. Log::Message(Log::LT_WARNING, "Syntax error parsing property declaration '%s: %s;' in %s: %d.", name.c_str(), value.c_str(), stream_file_name.c_str(), line_number);
  670. name.clear();
  671. value.clear();
  672. state = NAME;
  673. }
  674. else if (character == '}')
  675. {
  676. break;
  677. }
  678. else
  679. {
  680. value += character;
  681. if (character == '"')
  682. state = QUOTE;
  683. }
  684. }
  685. break;
  686. case QUOTE:
  687. {
  688. value += character;
  689. if (character == '"' && previous_character != '/')
  690. state = VALUE;
  691. }
  692. break;
  693. }
  694. if (character == '}')
  695. break;
  696. previous_character = character;
  697. }
  698. if (state == VALUE && !name.empty() && !value.empty())
  699. {
  700. value = StringUtilities::StripWhitespace(value);
  701. if (!property_parser.Parse(name, value))
  702. Log::Message(Log::LT_WARNING, "Syntax error parsing property declaration '%s: %s;' in %s: %d.", name.c_str(), value.c_str(), stream_file_name.c_str(), line_number);
  703. }
  704. else if (!name.empty() || !value.empty())
  705. {
  706. Log::Message(Log::LT_WARNING, "Invalid property declaration '%s':'%s' at %s:%d", name.c_str(), value.c_str(), stream_file_name.c_str(), line_number);
  707. }
  708. return true;
  709. }
  710. StyleSheetNode* StyleSheetParser::ImportProperties(StyleSheetNode* node, String rule_name, const PropertyDictionary& properties, int rule_specificity)
  711. {
  712. StyleSheetNode* leaf_node = node;
  713. StringList nodes;
  714. // Find child combinators, the RCSS '>' rule.
  715. size_t i_child = rule_name.find('>');
  716. while (i_child != String::npos)
  717. {
  718. // So we found one! Next, we want to format the rule such that the '>' is located at the
  719. // end of the left-hand-side node, and that there is a space to the right-hand-side. This ensures that
  720. // the selector is applied to the "parent", and that parent and child are expanded properly below.
  721. size_t i_begin = i_child;
  722. while (i_begin > 0 && rule_name[i_begin - 1] == ' ')
  723. i_begin--;
  724. const size_t i_end = i_child + 1;
  725. rule_name.replace(i_begin, i_end - i_begin, "> ");
  726. i_child = rule_name.find('>', i_begin + 1);
  727. }
  728. // Expand each individual node separated by spaces. Don't expand inside parenthesis because of structural selectors.
  729. StringUtilities::ExpandString(nodes, rule_name, ' ', '(', ')', true);
  730. // Create each node going down the tree
  731. for (size_t i = 0; i < nodes.size(); i++)
  732. {
  733. const String& name = nodes[i];
  734. String tag;
  735. String id;
  736. StringList classes;
  737. StringList pseudo_classes;
  738. StructuralSelectorList structural_pseudo_classes;
  739. bool child_combinator = false;
  740. size_t index = 0;
  741. while (index < name.size())
  742. {
  743. size_t start_index = index;
  744. size_t end_index = index + 1;
  745. // Read until we hit the next identifier.
  746. while (end_index < name.size() &&
  747. name[end_index] != '#' &&
  748. name[end_index] != '.' &&
  749. name[end_index] != ':' &&
  750. name[end_index] != '>')
  751. end_index++;
  752. String identifier = name.substr(start_index, end_index - start_index);
  753. if (!identifier.empty())
  754. {
  755. switch (identifier[0])
  756. {
  757. case '#': id = identifier.substr(1); break;
  758. case '.': classes.push_back(identifier.substr(1)); break;
  759. case ':':
  760. {
  761. String pseudo_class_name = identifier.substr(1);
  762. StructuralSelector node_selector = StyleSheetFactory::GetSelector(pseudo_class_name);
  763. if (node_selector.selector)
  764. structural_pseudo_classes.push_back(node_selector);
  765. else
  766. pseudo_classes.push_back(pseudo_class_name);
  767. }
  768. break;
  769. case '>': child_combinator = true; break;
  770. default: if(identifier != "*") tag = identifier;
  771. }
  772. }
  773. index = end_index;
  774. }
  775. // Sort the classes and pseudo-classes so they are consistent across equivalent declarations that shuffle the order around.
  776. std::sort(classes.begin(), classes.end());
  777. std::sort(pseudo_classes.begin(), pseudo_classes.end());
  778. std::sort(structural_pseudo_classes.begin(), structural_pseudo_classes.end());
  779. // Get the named child node.
  780. leaf_node = leaf_node->GetOrCreateChildNode(std::move(tag), std::move(id), std::move(classes), std::move(pseudo_classes), std::move(structural_pseudo_classes), child_combinator);
  781. }
  782. // Merge the new properties with those already on the leaf node.
  783. leaf_node->ImportProperties(properties, rule_specificity);
  784. return leaf_node;
  785. }
  786. char StyleSheetParser::FindToken(String& buffer, const char* tokens, bool remove_token)
  787. {
  788. buffer.clear();
  789. char character;
  790. while (ReadCharacter(character))
  791. {
  792. if (strchr(tokens, character) != nullptr)
  793. {
  794. if (remove_token)
  795. parse_buffer_pos++;
  796. return character;
  797. }
  798. else
  799. {
  800. buffer += character;
  801. parse_buffer_pos++;
  802. }
  803. }
  804. return 0;
  805. }
  806. // Attempts to find the next character in the active stream.
  807. bool StyleSheetParser::ReadCharacter(char& buffer)
  808. {
  809. bool comment = false;
  810. // Continuously fill the buffer until either we run out of
  811. // stream or we find the requested token
  812. do
  813. {
  814. while (parse_buffer_pos < parse_buffer.size())
  815. {
  816. if (parse_buffer[parse_buffer_pos] == '\n')
  817. line_number++;
  818. else if (comment)
  819. {
  820. // Check for closing comment
  821. if (parse_buffer[parse_buffer_pos] == '*')
  822. {
  823. parse_buffer_pos++;
  824. if (parse_buffer_pos >= parse_buffer.size())
  825. {
  826. if (!FillBuffer())
  827. return false;
  828. }
  829. if (parse_buffer[parse_buffer_pos] == '/')
  830. comment = false;
  831. }
  832. }
  833. else
  834. {
  835. // Check for an opening comment
  836. if (parse_buffer[parse_buffer_pos] == '/')
  837. {
  838. parse_buffer_pos++;
  839. if (parse_buffer_pos >= parse_buffer.size())
  840. {
  841. if (!FillBuffer())
  842. {
  843. buffer = '/';
  844. parse_buffer = "/";
  845. return true;
  846. }
  847. }
  848. if (parse_buffer[parse_buffer_pos] == '*')
  849. comment = true;
  850. else
  851. {
  852. buffer = '/';
  853. if (parse_buffer_pos == 0)
  854. parse_buffer.insert(parse_buffer_pos, 1, '/');
  855. else
  856. parse_buffer_pos--;
  857. return true;
  858. }
  859. }
  860. if (!comment)
  861. {
  862. // If we find a character, return it
  863. buffer = parse_buffer[parse_buffer_pos];
  864. return true;
  865. }
  866. }
  867. parse_buffer_pos++;
  868. }
  869. }
  870. while (FillBuffer());
  871. return false;
  872. }
  873. // Fills the internal buffer with more content
  874. bool StyleSheetParser::FillBuffer()
  875. {
  876. // If theres no data to process, abort
  877. if (stream->IsEOS())
  878. return false;
  879. // Read in some data (4092 instead of 4096 to avoid the buffer growing when we have to add back
  880. // a character after a failed comment parse.)
  881. parse_buffer.clear();
  882. bool read = stream->Read(parse_buffer, 4092) > 0;
  883. parse_buffer_pos = 0;
  884. return read;
  885. }
  886. } // namespace Rml