StyleSheetParser.cpp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  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. specification.RegisterProperty("theme", "", false, false, CastId(MediaQueryId::Theme)).AddParser("string");
  172. }
  173. void SetTargetProperties(PropertyDictionary* _properties)
  174. {
  175. properties = _properties;
  176. }
  177. void Clear() {
  178. properties = nullptr;
  179. }
  180. bool Parse(const String& name, const String& value) override
  181. {
  182. RMLUI_ASSERT(properties);
  183. return specification.ParsePropertyDeclaration(*properties, name, value);
  184. }
  185. };
  186. static UniquePtr<MediaQueryPropertyParser> media_query_property_parser;
  187. StyleSheetParser::StyleSheetParser()
  188. {
  189. line_number = 0;
  190. stream = nullptr;
  191. parse_buffer_pos = 0;
  192. }
  193. StyleSheetParser::~StyleSheetParser()
  194. {
  195. }
  196. void StyleSheetParser::Initialise()
  197. {
  198. spritesheet_property_parser = MakeUnique<SpritesheetPropertyParser>();
  199. media_query_property_parser = MakeUnique<MediaQueryPropertyParser>();
  200. }
  201. void StyleSheetParser::Shutdown()
  202. {
  203. spritesheet_property_parser.reset();
  204. media_query_property_parser.reset();
  205. }
  206. static bool IsValidIdentifier(const String& str)
  207. {
  208. if (str.empty())
  209. return false;
  210. for (size_t i = 0; i < str.size(); i++)
  211. {
  212. char c = str[i];
  213. bool valid = (
  214. (c >= 'a' && c <= 'z')
  215. || (c >= 'A' && c <= 'Z')
  216. || (c >= '0' && c <= '9')
  217. || (c == '-')
  218. || (c == '_')
  219. );
  220. if (!valid)
  221. return false;
  222. }
  223. return true;
  224. }
  225. static void PostprocessKeyframes(KeyframesMap& keyframes_map)
  226. {
  227. for (auto& keyframes_pair : keyframes_map)
  228. {
  229. Keyframes& keyframes = keyframes_pair.second;
  230. auto& blocks = keyframes.blocks;
  231. auto& property_ids = keyframes.property_ids;
  232. // Sort keyframes on selector value.
  233. std::sort(blocks.begin(), blocks.end(), [](const KeyframeBlock& a, const KeyframeBlock& b) { return a.normalized_time < b.normalized_time; });
  234. // Add all property names specified by any block
  235. if(blocks.size() > 0) property_ids.reserve(blocks.size() * blocks[0].properties.GetNumProperties());
  236. for(auto& block : blocks)
  237. {
  238. for (auto& property : block.properties.GetProperties())
  239. property_ids.push_back(property.first);
  240. }
  241. // Remove duplicate property names
  242. std::sort(property_ids.begin(), property_ids.end());
  243. property_ids.erase(std::unique(property_ids.begin(), property_ids.end()), property_ids.end());
  244. property_ids.shrink_to_fit();
  245. }
  246. }
  247. bool StyleSheetParser::ParseKeyframeBlock(KeyframesMap& keyframes_map, const String& identifier, const String& rules, const PropertyDictionary& properties)
  248. {
  249. if (!IsValidIdentifier(identifier))
  250. {
  251. Log::Message(Log::LT_WARNING, "Invalid keyframes identifier '%s' at %s:%d", identifier.c_str(), stream_file_name.c_str(), line_number);
  252. return false;
  253. }
  254. if (properties.GetNumProperties() == 0)
  255. return true;
  256. StringList rule_list;
  257. StringUtilities::ExpandString(rule_list, rules);
  258. Vector<float> rule_values;
  259. rule_values.reserve(rule_list.size());
  260. for (auto rule : rule_list)
  261. {
  262. float value = 0.0f;
  263. int count = 0;
  264. rule = StringUtilities::ToLower(rule);
  265. if (rule == "from")
  266. rule_values.push_back(0.0f);
  267. else if (rule == "to")
  268. rule_values.push_back(1.0f);
  269. else if(sscanf(rule.c_str(), "%f%%%n", &value, &count) == 1)
  270. if(count > 0 && value >= 0.0f && value <= 100.0f)
  271. rule_values.push_back(0.01f * value);
  272. }
  273. if (rule_values.empty())
  274. {
  275. Log::Message(Log::LT_WARNING, "Invalid keyframes rule(s) '%s' at %s:%d", rules.c_str(), stream_file_name.c_str(), line_number);
  276. return false;
  277. }
  278. Keyframes& keyframes = keyframes_map[identifier];
  279. for(float selector : rule_values)
  280. {
  281. 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; });
  282. if (it == keyframes.blocks.end())
  283. {
  284. keyframes.blocks.emplace_back(selector);
  285. it = (keyframes.blocks.end() - 1);
  286. }
  287. else
  288. {
  289. // In case of duplicate keyframes, we only use the latest definition as per CSS rules
  290. it->properties = PropertyDictionary();
  291. }
  292. it->properties.Import(properties);
  293. }
  294. return true;
  295. }
  296. bool StyleSheetParser::ParseDecoratorBlock(const String& at_name, DecoratorSpecificationMap& decorator_map, const StyleSheet& style_sheet, const SharedPtr<const PropertySource>& source)
  297. {
  298. StringList name_type;
  299. StringUtilities::ExpandString(name_type, at_name, ':');
  300. if (name_type.size() != 2 || name_type[0].empty() || name_type[1].empty())
  301. {
  302. Log::Message(Log::LT_WARNING, "Decorator syntax error at %s:%d. Use syntax: '@decorator name : type { ... }'.", stream_file_name.c_str(), line_number);
  303. return false;
  304. }
  305. const String& name = name_type[0];
  306. String decorator_type = name_type[1];
  307. auto it_find = decorator_map.find(name);
  308. if (it_find != decorator_map.end())
  309. {
  310. 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);
  311. return false;
  312. }
  313. // Get the instancer associated with the decorator type
  314. DecoratorInstancer* decorator_instancer = Factory::GetDecoratorInstancer(decorator_type);
  315. PropertyDictionary properties;
  316. if(!decorator_instancer)
  317. {
  318. // Type is not a declared decorator type, instead, see if it is another decorator name, then we inherit its properties.
  319. auto it = decorator_map.find(decorator_type);
  320. if (it != decorator_map.end())
  321. {
  322. // Yes, try to retrieve the instancer from the parent type, and add its property values.
  323. decorator_instancer = Factory::GetDecoratorInstancer(it->second.decorator_type);
  324. properties = it->second.properties;
  325. decorator_type = it->second.decorator_type;
  326. }
  327. // If we still don't have an instancer, we cannot continue.
  328. if (!decorator_instancer)
  329. {
  330. Log::Message(Log::LT_WARNING, "Invalid decorator type '%s' declared at %s:%d.", decorator_type.c_str(), stream_file_name.c_str(), line_number);
  331. return false;
  332. }
  333. }
  334. const PropertySpecification& property_specification = decorator_instancer->GetPropertySpecification();
  335. PropertySpecificationParser parser(properties, property_specification);
  336. if (!ReadProperties(parser))
  337. return false;
  338. // Set non-defined properties to their defaults
  339. property_specification.SetPropertyDefaults(properties);
  340. properties.SetSourceOfAllProperties(source);
  341. SharedPtr<Decorator> decorator = decorator_instancer->InstanceDecorator(decorator_type, properties, DecoratorInstancerInterface(style_sheet, source.get()));
  342. if (!decorator)
  343. {
  344. 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);
  345. return false;
  346. }
  347. decorator_map.emplace(name, DecoratorSpecification{ std::move(decorator_type), std::move(properties), std::move(decorator) });
  348. return true;
  349. }
  350. bool StyleSheetParser::ParseMediaFeatureMap(PropertyDictionary& properties, const String & rules)
  351. {
  352. media_query_property_parser->SetTargetProperties(&properties);
  353. enum ParseState { Global, Name, Value };
  354. ParseState state = Name;
  355. char character = 0;
  356. size_t cursor = 0;
  357. String name;
  358. String current_string;
  359. while(cursor++ < rules.length())
  360. {
  361. character = rules[cursor];
  362. switch(character)
  363. {
  364. case '(':
  365. {
  366. if (state != Global)
  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(StringUtilities::ToLower(current_string));
  372. if (current_string != "and")
  373. {
  374. 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);
  375. return false;
  376. }
  377. current_string.clear();
  378. state = Name;
  379. }
  380. break;
  381. case ')':
  382. {
  383. if (state != Value)
  384. {
  385. Log::Message(Log::LT_WARNING, "Unexpected ')' in @media query list at %s:%d.", stream_file_name.c_str(), line_number);
  386. return false;
  387. }
  388. current_string = StringUtilities::StripWhitespace(current_string);
  389. if(!media_query_property_parser->Parse(name, current_string))
  390. 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);
  391. current_string.clear();
  392. state = Global;
  393. }
  394. break;
  395. case ':':
  396. {
  397. if (state != Name)
  398. {
  399. Log::Message(Log::LT_WARNING, "Unexpected ':' in @media query list at %s:%d.", stream_file_name.c_str(), line_number);
  400. return false;
  401. }
  402. current_string = StringUtilities::StripWhitespace(StringUtilities::ToLower(current_string));
  403. if (!IsValidIdentifier(current_string))
  404. {
  405. 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);
  406. return false;
  407. }
  408. name = current_string;
  409. current_string.clear();
  410. state = Value;
  411. }
  412. break;
  413. default:
  414. current_string += character;
  415. }
  416. }
  417. if (properties.GetNumProperties() == 0)
  418. {
  419. Log::Message(Log::LT_WARNING, "Media query list parsing yielded no properties at %s:%d.", stream_file_name.c_str(), line_number);
  420. }
  421. return true;
  422. }
  423. bool StyleSheetParser::Parse(MediaBlockList& style_sheets, Stream* _stream, int begin_line_number)
  424. {
  425. RMLUI_ZoneScoped;
  426. int rule_count = 0;
  427. line_number = begin_line_number;
  428. stream = _stream;
  429. stream_file_name = StringUtilities::Replace(stream->GetSourceURL().GetURL(), '|', ':');
  430. enum class State { Global, AtRuleIdentifier, KeyframeBlock, Invalid };
  431. State state = State::Global;
  432. MediaBlock current_block = {};
  433. // Need to track whether currently inside a nested media block or not, since the default scope is also a media block
  434. bool inside_media_block = false;
  435. // At-rules given by the following syntax in global space: @identifier name { block }
  436. String at_rule_name;
  437. // Look for more styles while data is available
  438. while (FillBuffer())
  439. {
  440. String pre_token_str;
  441. while (char token = FindToken(pre_token_str, "{@}", true))
  442. {
  443. switch (state)
  444. {
  445. case State::Global:
  446. {
  447. if (token == '{')
  448. {
  449. // Initialize current block if not present
  450. if (!current_block.stylesheet)
  451. {
  452. current_block = MediaBlock{PropertyDictionary{}, UniquePtr<StyleSheet>(new StyleSheet())};
  453. }
  454. const int rule_line_number = line_number;
  455. // Read the attributes
  456. PropertyDictionary properties;
  457. PropertySpecificationParser parser(properties, StyleSheetSpecification::GetPropertySpecification());
  458. if (!ReadProperties(parser))
  459. continue;
  460. StringList rule_name_list;
  461. StringUtilities::ExpandString(rule_name_list, pre_token_str, ',', '(', ')');
  462. // Add style nodes to the root of the tree
  463. for (size_t i = 0; i < rule_name_list.size(); i++)
  464. {
  465. auto source = MakeShared<PropertySource>(stream_file_name, rule_line_number, rule_name_list[i]);
  466. properties.SetSourceOfAllProperties(source);
  467. ImportProperties(current_block.stylesheet->root.get(), rule_name_list[i], properties, rule_count);
  468. }
  469. rule_count++;
  470. }
  471. else if (token == '@')
  472. {
  473. state = State::AtRuleIdentifier;
  474. }
  475. else if (inside_media_block && token == '}')
  476. {
  477. // Complete current block
  478. PostprocessKeyframes(current_block.stylesheet->keyframes);
  479. current_block.stylesheet->specificity_offset = rule_count;
  480. style_sheets.push_back(std::move(current_block));
  481. current_block = {};
  482. inside_media_block = false;
  483. break;
  484. }
  485. else
  486. {
  487. 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);
  488. }
  489. }
  490. break;
  491. case State::AtRuleIdentifier:
  492. {
  493. if (token == '{')
  494. {
  495. // Initialize current block if not present
  496. if (!current_block.stylesheet)
  497. {
  498. current_block = {PropertyDictionary{}, UniquePtr<StyleSheet>(new StyleSheet())};
  499. }
  500. const String at_rule_identifier = StringUtilities::StripWhitespace(pre_token_str.substr(0, pre_token_str.find(' ')));
  501. at_rule_name = StringUtilities::StripWhitespace(pre_token_str.substr(at_rule_identifier.size()));
  502. if (at_rule_identifier == "keyframes")
  503. {
  504. state = State::KeyframeBlock;
  505. }
  506. else if (at_rule_identifier == "decorator")
  507. {
  508. auto source = MakeShared<PropertySource>(stream_file_name, (int)line_number, pre_token_str);
  509. ParseDecoratorBlock(at_rule_name, current_block.stylesheet->decorator_map, *current_block.stylesheet, source);
  510. at_rule_name.clear();
  511. state = State::Global;
  512. }
  513. else if (at_rule_identifier == "spritesheet")
  514. {
  515. // The spritesheet parser is reasonably heavy to initialize, so we make it a static global.
  516. ReadProperties(*spritesheet_property_parser);
  517. const String& image_source = spritesheet_property_parser->GetImageSource();
  518. const SpriteDefinitionList& sprite_definitions = spritesheet_property_parser->GetSpriteDefinitions();
  519. const float image_resolution_factor = spritesheet_property_parser->GetImageResolutionFactor();
  520. if (sprite_definitions.empty())
  521. {
  522. 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);
  523. }
  524. else if (image_source.empty())
  525. {
  526. 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);
  527. }
  528. else if (image_resolution_factor <= 0.0f || image_resolution_factor >= 100.f)
  529. {
  530. 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);
  531. }
  532. else
  533. {
  534. const float display_scale = 1.0f / image_resolution_factor;
  535. current_block.stylesheet->spritesheet_list.AddSpriteSheet(at_rule_name, image_source, stream_file_name, (int)line_number, display_scale, sprite_definitions);
  536. }
  537. spritesheet_property_parser->Clear();
  538. at_rule_name.clear();
  539. state = State::Global;
  540. }
  541. else if (at_rule_identifier == "media")
  542. {
  543. // complete the current "global" block if present and start a new block
  544. if (current_block.stylesheet)
  545. {
  546. PostprocessKeyframes(current_block.stylesheet->keyframes);
  547. current_block.stylesheet->specificity_offset = rule_count;
  548. style_sheets.push_back(std::move(current_block));
  549. current_block = {};
  550. }
  551. // parse media query list into block
  552. PropertyDictionary feature_map;
  553. ParseMediaFeatureMap(feature_map, at_rule_name);
  554. current_block = {std::move(feature_map), UniquePtr<StyleSheet>(new StyleSheet())};
  555. inside_media_block = true;
  556. state = State::Global;
  557. }
  558. else
  559. {
  560. // Invalid identifier, should ignore
  561. at_rule_name.clear();
  562. state = State::Global;
  563. 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);
  564. }
  565. }
  566. else
  567. {
  568. 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);
  569. state = State::Invalid;
  570. }
  571. }
  572. break;
  573. case State::KeyframeBlock:
  574. {
  575. if (token == '{')
  576. {
  577. // Initialize current block if not present
  578. if (!current_block.stylesheet)
  579. {
  580. current_block = {PropertyDictionary{}, UniquePtr<StyleSheet>(new StyleSheet())};
  581. }
  582. // Each keyframe in keyframes has its own block which is processed here
  583. PropertyDictionary properties;
  584. PropertySpecificationParser parser(properties, StyleSheetSpecification::GetPropertySpecification());
  585. if(!ReadProperties(parser))
  586. continue;
  587. if (!ParseKeyframeBlock(current_block.stylesheet->keyframes, at_rule_name, pre_token_str, properties))
  588. continue;
  589. }
  590. else if (token == '}')
  591. {
  592. at_rule_name.clear();
  593. state = State::Global;
  594. }
  595. else
  596. {
  597. 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);
  598. state = State::Invalid;
  599. }
  600. }
  601. break;
  602. default:
  603. RMLUI_ERROR;
  604. state = State::Invalid;
  605. break;
  606. }
  607. if (state == State::Invalid)
  608. break;
  609. }
  610. if (state == State::Invalid)
  611. break;
  612. }
  613. // Complete last block if present
  614. if (current_block.stylesheet)
  615. {
  616. PostprocessKeyframes(current_block.stylesheet->keyframes);
  617. current_block.stylesheet->specificity_offset = rule_count;
  618. style_sheets.push_back(std::move(current_block));
  619. }
  620. return !style_sheets.empty();
  621. }
  622. bool StyleSheetParser::ParseProperties(PropertyDictionary& parsed_properties, const String& properties)
  623. {
  624. RMLUI_ASSERT(!stream);
  625. StreamMemory stream_owner((const byte*)properties.c_str(), properties.size());
  626. stream = &stream_owner;
  627. PropertySpecificationParser parser(parsed_properties, StyleSheetSpecification::GetPropertySpecification());
  628. bool success = ReadProperties(parser);
  629. stream = nullptr;
  630. return success;
  631. }
  632. StyleSheetNodeListRaw StyleSheetParser::ConstructNodes(StyleSheetNode& root_node, const String& selectors)
  633. {
  634. const PropertyDictionary empty_properties;
  635. StringList selector_list;
  636. StringUtilities::ExpandString(selector_list, selectors, ',', '(', ')');
  637. StyleSheetNodeListRaw leaf_nodes;
  638. for (const String& selector : selector_list)
  639. {
  640. StyleSheetNode* leaf_node = ImportProperties(&root_node, selector, empty_properties, 0);
  641. if (leaf_node != &root_node)
  642. leaf_nodes.push_back(leaf_node);
  643. }
  644. return leaf_nodes;
  645. }
  646. bool 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(), stream_file_name.c_str(), line_number);
  668. name.clear();
  669. }
  670. }
  671. else if (character == '}')
  672. {
  673. name = StringUtilities::StripWhitespace(name);
  674. if (!name.empty())
  675. 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);
  676. return true;
  677. }
  678. else if (character == ':')
  679. {
  680. name = StringUtilities::StripWhitespace(name);
  681. state = VALUE;
  682. }
  683. else
  684. name += character;
  685. }
  686. break;
  687. case VALUE:
  688. {
  689. if (character == ';')
  690. {
  691. value = StringUtilities::StripWhitespace(value);
  692. if (!property_parser.Parse(name, value))
  693. 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);
  694. name.clear();
  695. value.clear();
  696. state = NAME;
  697. }
  698. else if (character == '}')
  699. {
  700. break;
  701. }
  702. else
  703. {
  704. value += character;
  705. if (character == '"')
  706. state = QUOTE;
  707. }
  708. }
  709. break;
  710. case QUOTE:
  711. {
  712. value += character;
  713. if (character == '"' && previous_character != '\\')
  714. state = VALUE;
  715. }
  716. break;
  717. }
  718. if (character == '}')
  719. break;
  720. previous_character = character;
  721. }
  722. if (state == VALUE && !name.empty() && !value.empty())
  723. {
  724. value = StringUtilities::StripWhitespace(value);
  725. if (!property_parser.Parse(name, value))
  726. 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);
  727. }
  728. else if (!StringUtilities::StripWhitespace(name).empty() || !value.empty())
  729. {
  730. 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);
  731. }
  732. return true;
  733. }
  734. StyleSheetNode* StyleSheetParser::ImportProperties(StyleSheetNode* node, const String& rule, const PropertyDictionary& properties,
  735. int rule_specificity)
  736. {
  737. StyleSheetNode* leaf_node = node;
  738. // Create each node going down the tree.
  739. for (size_t index = 0; index < rule.size();)
  740. {
  741. // Determine the combinator connecting the previous node if any.
  742. SelectorCombinator combinator = SelectorCombinator::Descendant;
  743. for (; index > 0 && index < rule.size(); index++)
  744. {
  745. bool reached_end_of_combinators = false;
  746. switch (rule[index])
  747. {
  748. case ' ': break;
  749. case '>': combinator = SelectorCombinator::Child; break;
  750. case '+': combinator = SelectorCombinator::NextSibling; break;
  751. case '~': combinator = SelectorCombinator::SubsequentSibling; break;
  752. default: reached_end_of_combinators = true; break;
  753. }
  754. if (reached_end_of_combinators)
  755. break;
  756. }
  757. String tag;
  758. String id;
  759. StringList classes;
  760. StringList pseudo_classes;
  761. StructuralSelectorList structural_pseudo_classes;
  762. // Determine the node's requirements.
  763. while (index < rule.size())
  764. {
  765. size_t start_index = index;
  766. size_t end_index = index + 1;
  767. int parenthesis_count = 0;
  768. // Read until we hit the next identifier. Don't match inside parenthesis in case of structural selectors.
  769. for (; end_index < rule.size(); end_index++)
  770. {
  771. static const String identifiers = "#.: >+~";
  772. if (parenthesis_count == 0 && identifiers.find(rule[end_index]) != String::npos)
  773. break;
  774. if (rule[end_index] == '(')
  775. parenthesis_count += 1;
  776. else if (rule[end_index] == ')')
  777. parenthesis_count -= 1;
  778. }
  779. if (rule[start_index] == '*')
  780. start_index += 1;
  781. StringView identifier = StringView(rule, start_index, end_index - start_index);
  782. if (identifier.size() > 0)
  783. {
  784. switch (*identifier.begin())
  785. {
  786. case '#': id = String(identifier.begin() + 1, identifier.end()); break;
  787. case '.': classes.push_back(String(identifier.begin() + 1, identifier.end())); break;
  788. case ':':
  789. {
  790. String pseudo_class_name = String(identifier.begin() + 1, identifier.end());
  791. StructuralSelector node_selector = StyleSheetFactory::GetSelector(pseudo_class_name);
  792. if (node_selector.type != StructuralSelectorType::Invalid)
  793. structural_pseudo_classes.push_back(node_selector);
  794. else
  795. pseudo_classes.push_back(std::move(pseudo_class_name));
  796. }
  797. break;
  798. default: tag = String(identifier);
  799. }
  800. }
  801. index = end_index;
  802. // If we reached a combinator then we submit the current node and start fresh with a new node.
  803. static const String combinators(" >+~");
  804. if (combinators.find(rule[index]) != String::npos)
  805. break;
  806. }
  807. // Sort the classes and pseudo-classes so they are consistent across equivalent declarations that shuffle the order around.
  808. std::sort(classes.begin(), classes.end());
  809. std::sort(pseudo_classes.begin(), pseudo_classes.end());
  810. std::sort(structural_pseudo_classes.begin(), structural_pseudo_classes.end());
  811. // Add the new child node, or retrieve the existing child if we have an exact match.
  812. leaf_node = leaf_node->GetOrCreateChildNode(std::move(tag), std::move(id), std::move(classes), std::move(pseudo_classes),
  813. std::move(structural_pseudo_classes), combinator);
  814. }
  815. // Merge the new properties with those already on the leaf node.
  816. leaf_node->ImportProperties(properties, rule_specificity);
  817. return leaf_node;
  818. }
  819. char StyleSheetParser::FindToken(String& buffer, const char* tokens, bool remove_token)
  820. {
  821. buffer.clear();
  822. char character;
  823. while (ReadCharacter(character))
  824. {
  825. if (strchr(tokens, character) != nullptr)
  826. {
  827. if (remove_token)
  828. parse_buffer_pos++;
  829. return character;
  830. }
  831. else
  832. {
  833. buffer += character;
  834. parse_buffer_pos++;
  835. }
  836. }
  837. return 0;
  838. }
  839. // Attempts to find the next character in the active stream.
  840. bool StyleSheetParser::ReadCharacter(char& buffer)
  841. {
  842. bool comment = false;
  843. // Continuously fill the buffer until either we run out of
  844. // stream or we find the requested token
  845. do
  846. {
  847. while (parse_buffer_pos < parse_buffer.size())
  848. {
  849. if (parse_buffer[parse_buffer_pos] == '\n')
  850. line_number++;
  851. else if (comment)
  852. {
  853. // Check for closing comment
  854. if (parse_buffer[parse_buffer_pos] == '*')
  855. {
  856. parse_buffer_pos++;
  857. if (parse_buffer_pos >= parse_buffer.size())
  858. {
  859. if (!FillBuffer())
  860. return false;
  861. }
  862. if (parse_buffer[parse_buffer_pos] == '/')
  863. comment = false;
  864. }
  865. }
  866. else
  867. {
  868. // Check for an opening comment
  869. if (parse_buffer[parse_buffer_pos] == '/')
  870. {
  871. parse_buffer_pos++;
  872. if (parse_buffer_pos >= parse_buffer.size())
  873. {
  874. if (!FillBuffer())
  875. {
  876. buffer = '/';
  877. parse_buffer = "/";
  878. return true;
  879. }
  880. }
  881. if (parse_buffer[parse_buffer_pos] == '*')
  882. comment = true;
  883. else
  884. {
  885. buffer = '/';
  886. if (parse_buffer_pos == 0)
  887. parse_buffer.insert(parse_buffer_pos, 1, '/');
  888. else
  889. parse_buffer_pos--;
  890. return true;
  891. }
  892. }
  893. if (!comment)
  894. {
  895. // If we find a character, return it
  896. buffer = parse_buffer[parse_buffer_pos];
  897. return true;
  898. }
  899. }
  900. parse_buffer_pos++;
  901. }
  902. }
  903. while (FillBuffer());
  904. return false;
  905. }
  906. // Fills the internal buffer with more content
  907. bool StyleSheetParser::FillBuffer()
  908. {
  909. // If theres no data to process, abort
  910. if (stream->IsEOS())
  911. return false;
  912. // Read in some data (4092 instead of 4096 to avoid the buffer growing when we have to add back
  913. // a character after a failed comment parse.)
  914. parse_buffer.clear();
  915. bool read = stream->Read(parse_buffer, 4092) > 0;
  916. parse_buffer_pos = 0;
  917. return read;
  918. }
  919. } // namespace Rml