StyleSheetParser.cpp 19 KB

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