StyleSheetParser.cpp 24 KB

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