StyleSheetParser.cpp 33 KB

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