StyleSheetParser.cpp 24 KB

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