StyleSheetParser.cpp 25 KB

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