StyleSheetParser.cpp 34 KB

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