StyleSheetParser.cpp 25 KB

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