2
0

StyleSheetParser.cpp 22 KB

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