StyleSheetParser.cpp 23 KB

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