StyleSheetParser.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077
  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 (!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, String rule_name, const PropertyDictionary& properties, int rule_specificity)
  735. {
  736. StyleSheetNode* leaf_node = node;
  737. StringList nodes;
  738. // Find child combinators, the RCSS '>' rule.
  739. size_t i_child = rule_name.find('>');
  740. while (i_child != String::npos)
  741. {
  742. // So we found one! Next, we want to format the rule such that the '>' is located at the
  743. // end of the left-hand-side node, and that there is a space to the right-hand-side. This ensures that
  744. // the selector is applied to the "parent", and that parent and child are expanded properly below.
  745. size_t i_begin = i_child;
  746. while (i_begin > 0 && rule_name[i_begin - 1] == ' ')
  747. i_begin--;
  748. const size_t i_end = i_child + 1;
  749. rule_name.replace(i_begin, i_end - i_begin, "> ");
  750. i_child = rule_name.find('>', i_begin + 1);
  751. }
  752. // Expand each individual node separated by spaces. Don't expand inside parenthesis because of structural selectors.
  753. StringUtilities::ExpandString(nodes, rule_name, ' ', '(', ')', true);
  754. // Create each node going down the tree
  755. for (size_t i = 0; i < nodes.size(); i++)
  756. {
  757. const String& name = nodes[i];
  758. String tag;
  759. String id;
  760. StringList classes;
  761. StringList pseudo_classes;
  762. StructuralSelectorList structural_pseudo_classes;
  763. bool child_combinator = false;
  764. size_t index = 0;
  765. while (index < name.size())
  766. {
  767. size_t start_index = index;
  768. size_t end_index = index + 1;
  769. // Read until we hit the next identifier.
  770. while (end_index < name.size() &&
  771. name[end_index] != '#' &&
  772. name[end_index] != '.' &&
  773. name[end_index] != ':' &&
  774. name[end_index] != '>')
  775. end_index++;
  776. String identifier = name.substr(start_index, end_index - start_index);
  777. if (!identifier.empty())
  778. {
  779. switch (identifier[0])
  780. {
  781. case '#': id = identifier.substr(1); break;
  782. case '.': classes.push_back(identifier.substr(1)); break;
  783. case ':':
  784. {
  785. String pseudo_class_name = identifier.substr(1);
  786. StructuralSelector node_selector = StyleSheetFactory::GetSelector(pseudo_class_name);
  787. if (node_selector.selector)
  788. structural_pseudo_classes.push_back(node_selector);
  789. else
  790. pseudo_classes.push_back(pseudo_class_name);
  791. }
  792. break;
  793. case '>': child_combinator = true; break;
  794. default: if(identifier != "*") tag = identifier;
  795. }
  796. }
  797. index = end_index;
  798. }
  799. // Sort the classes and pseudo-classes so they are consistent across equivalent declarations that shuffle the order around.
  800. std::sort(classes.begin(), classes.end());
  801. std::sort(pseudo_classes.begin(), pseudo_classes.end());
  802. std::sort(structural_pseudo_classes.begin(), structural_pseudo_classes.end());
  803. // Get the named child node.
  804. 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);
  805. }
  806. // Merge the new properties with those already on the leaf node.
  807. leaf_node->ImportProperties(properties, rule_specificity);
  808. return leaf_node;
  809. }
  810. char StyleSheetParser::FindToken(String& buffer, const char* tokens, bool remove_token)
  811. {
  812. buffer.clear();
  813. char character;
  814. while (ReadCharacter(character))
  815. {
  816. if (strchr(tokens, character) != nullptr)
  817. {
  818. if (remove_token)
  819. parse_buffer_pos++;
  820. return character;
  821. }
  822. else
  823. {
  824. buffer += character;
  825. parse_buffer_pos++;
  826. }
  827. }
  828. return 0;
  829. }
  830. // Attempts to find the next character in the active stream.
  831. bool StyleSheetParser::ReadCharacter(char& buffer)
  832. {
  833. bool comment = false;
  834. // Continuously fill the buffer until either we run out of
  835. // stream or we find the requested token
  836. do
  837. {
  838. while (parse_buffer_pos < parse_buffer.size())
  839. {
  840. if (parse_buffer[parse_buffer_pos] == '\n')
  841. line_number++;
  842. else if (comment)
  843. {
  844. // Check for closing comment
  845. if (parse_buffer[parse_buffer_pos] == '*')
  846. {
  847. parse_buffer_pos++;
  848. if (parse_buffer_pos >= parse_buffer.size())
  849. {
  850. if (!FillBuffer())
  851. return false;
  852. }
  853. if (parse_buffer[parse_buffer_pos] == '/')
  854. comment = false;
  855. }
  856. }
  857. else
  858. {
  859. // Check for an opening comment
  860. if (parse_buffer[parse_buffer_pos] == '/')
  861. {
  862. parse_buffer_pos++;
  863. if (parse_buffer_pos >= parse_buffer.size())
  864. {
  865. if (!FillBuffer())
  866. {
  867. buffer = '/';
  868. parse_buffer = "/";
  869. return true;
  870. }
  871. }
  872. if (parse_buffer[parse_buffer_pos] == '*')
  873. comment = true;
  874. else
  875. {
  876. buffer = '/';
  877. if (parse_buffer_pos == 0)
  878. parse_buffer.insert(parse_buffer_pos, 1, '/');
  879. else
  880. parse_buffer_pos--;
  881. return true;
  882. }
  883. }
  884. if (!comment)
  885. {
  886. // If we find a character, return it
  887. buffer = parse_buffer[parse_buffer_pos];
  888. return true;
  889. }
  890. }
  891. parse_buffer_pos++;
  892. }
  893. }
  894. while (FillBuffer());
  895. return false;
  896. }
  897. // Fills the internal buffer with more content
  898. bool StyleSheetParser::FillBuffer()
  899. {
  900. // If theres no data to process, abort
  901. if (stream->IsEOS())
  902. return false;
  903. // Read in some data (4092 instead of 4096 to avoid the buffer growing when we have to add back
  904. // a character after a failed comment parse.)
  905. parse_buffer.clear();
  906. bool read = stream->Read(parse_buffer, 4092) > 0;
  907. parse_buffer_pos = 0;
  908. return read;
  909. }
  910. } // namespace Rml