StyleSheetParser.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  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->second.decorator_type);
  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. // Set non-defined properties to their defaults
  178. property_specification->SetPropertyDefaults(properties);
  179. Decorator* decorator = Factory::InstanceDecorator(decorator_type, properties);
  180. if (!decorator)
  181. {
  182. 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);
  183. return false;
  184. }
  185. decorator_map.emplace(name, DecoratorSpecification{ std::move(decorator_type), std::move(properties), decorator });
  186. return true;
  187. }
  188. int StyleSheetParser::Parse(StyleSheetNode* node, KeyframesMap& keyframes, DecoratorSpecificationMap& decorator_map, Stream* _stream)
  189. {
  190. int rule_count = 0;
  191. line_number = 0;
  192. stream = _stream;
  193. stream_file_name = Replace(stream->GetSourceURL().GetURL(), "|", ":");
  194. enum class State { Global, AtRuleIdentifier, KeyframeBlock, Invalid };
  195. State state = State::Global;
  196. // At-rules given by the following syntax in global space: @identifier name { block }
  197. String at_rule_name;
  198. // Look for more styles while data is available
  199. while (FillBuffer())
  200. {
  201. String pre_token_str;
  202. while (char token = FindToken(pre_token_str, "{@}", true))
  203. {
  204. switch (state)
  205. {
  206. case State::Global:
  207. {
  208. if (token == '{')
  209. {
  210. // Read the attributes
  211. PropertyDictionary properties;
  212. if (!ReadProperties(properties, StyleSheetSpecification::GetPropertySpecification()))
  213. continue;
  214. StringList style_name_list;
  215. StringUtilities::ExpandString(style_name_list, pre_token_str);
  216. // Add style nodes to the root of the tree
  217. for (size_t i = 0; i < style_name_list.size(); i++)
  218. ImportProperties(node, style_name_list[i], properties, rule_count);
  219. rule_count++;
  220. }
  221. else if (token == '@')
  222. {
  223. state = State::AtRuleIdentifier;
  224. }
  225. else
  226. {
  227. 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);
  228. }
  229. }
  230. break;
  231. case State::AtRuleIdentifier:
  232. {
  233. if (token == '{')
  234. {
  235. String at_rule_identifier = pre_token_str.substr(0, pre_token_str.find(' '));
  236. at_rule_name = StringUtilities::StripWhitespace(pre_token_str.substr(at_rule_identifier.size()));
  237. if (at_rule_identifier == KEYFRAMES)
  238. {
  239. state = State::KeyframeBlock;
  240. }
  241. else if (at_rule_identifier == "decorator")
  242. {
  243. ParseDecoratorBlock(decorator_map, at_rule_name);
  244. at_rule_name.clear();
  245. state = State::Global;
  246. }
  247. else
  248. {
  249. // Invalid identifier, should ignore
  250. at_rule_name.clear();
  251. state = State::Global;
  252. 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);
  253. }
  254. }
  255. else
  256. {
  257. 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);
  258. state = State::Invalid;
  259. }
  260. }
  261. break;
  262. case State::KeyframeBlock:
  263. {
  264. if (token == '{')
  265. {
  266. // Each keyframe in keyframes has its own block which is processed here
  267. PropertyDictionary properties;
  268. if (!ReadProperties(properties, StyleSheetSpecification::GetPropertySpecification()))
  269. continue;
  270. if (!ParseKeyframeBlock(keyframes, at_rule_name, pre_token_str, properties))
  271. continue;
  272. }
  273. else if (token == '}')
  274. {
  275. at_rule_name.clear();
  276. state = State::Global;
  277. }
  278. else
  279. {
  280. 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);
  281. state = State::Invalid;
  282. }
  283. }
  284. break;
  285. default:
  286. ROCKET_ERROR;
  287. state = State::Invalid;
  288. break;
  289. }
  290. if (state == State::Invalid)
  291. break;
  292. }
  293. if (state == State::Invalid)
  294. break;
  295. }
  296. PostprocessKeyframes(keyframes);
  297. return rule_count;
  298. }
  299. bool StyleSheetParser::ParseProperties(PropertyDictionary& parsed_properties, const String& properties)
  300. {
  301. stream = new StreamMemory((const byte*)properties.c_str(), properties.size());
  302. bool success = ReadProperties(parsed_properties, StyleSheetSpecification::GetPropertySpecification());
  303. stream->RemoveReference();
  304. stream = NULL;
  305. return success;
  306. }
  307. bool StyleSheetParser::ReadProperties(PropertyDictionary& properties, const PropertySpecification& property_specification)
  308. {
  309. int rule_line_number = (int)line_number;
  310. String name;
  311. String value;
  312. enum ParseState { NAME, VALUE, QUOTE };
  313. ParseState state = NAME;
  314. char character;
  315. char previous_character = 0;
  316. while (ReadCharacter(character))
  317. {
  318. parse_buffer_pos++;
  319. switch (state)
  320. {
  321. case NAME:
  322. {
  323. if (character == ';')
  324. {
  325. name = StringUtilities::StripWhitespace(name);
  326. if (!name.empty())
  327. {
  328. 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);
  329. name.clear();
  330. }
  331. }
  332. else if (character == '}')
  333. {
  334. name = StringUtilities::StripWhitespace(name);
  335. if (!StringUtilities::StripWhitespace(name).empty())
  336. 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);
  337. return true;
  338. }
  339. else if (character == ':')
  340. {
  341. name = StringUtilities::StripWhitespace(name);
  342. state = VALUE;
  343. }
  344. else
  345. name += character;
  346. }
  347. break;
  348. case VALUE:
  349. {
  350. if (character == ';')
  351. {
  352. value = StringUtilities::StripWhitespace(value);
  353. if (!property_specification.ParsePropertyDeclaration(properties, name, value, stream_file_name, rule_line_number))
  354. 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);
  355. name.clear();
  356. value.clear();
  357. state = NAME;
  358. }
  359. else if (character == '}')
  360. {
  361. 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);
  362. return true;
  363. }
  364. else
  365. {
  366. value += character;
  367. if (character == '"')
  368. state = QUOTE;
  369. }
  370. }
  371. break;
  372. case QUOTE:
  373. {
  374. value += character;
  375. if (character == '"' && previous_character != '/')
  376. state = VALUE;
  377. }
  378. break;
  379. }
  380. previous_character = character;
  381. }
  382. if (!name.empty() || !value.empty())
  383. 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);
  384. return true;
  385. }
  386. // Updates the StyleNode tree, creating new nodes as necessary, setting the definition index
  387. bool StyleSheetParser::ImportProperties(StyleSheetNode* node, const String& names, const PropertyDictionary& properties, int rule_specificity)
  388. {
  389. StyleSheetNode* tag_node = NULL;
  390. StyleSheetNode* leaf_node = node;
  391. StringList nodes;
  392. StringUtilities::ExpandString(nodes, names, ' ');
  393. // Create each node going down the tree
  394. for (size_t i = 0; i < nodes.size(); i++)
  395. {
  396. String name = nodes[i];
  397. String tag;
  398. String id;
  399. StringList classes;
  400. StringList pseudo_classes;
  401. StringList structural_pseudo_classes;
  402. size_t index = 0;
  403. while (index < name.size())
  404. {
  405. size_t start_index = index;
  406. size_t end_index = index + 1;
  407. // Read until we hit the next identifier.
  408. while (end_index < name.size() &&
  409. name[end_index] != '#' &&
  410. name[end_index] != '.' &&
  411. name[end_index] != ':')
  412. end_index++;
  413. String identifier = name.substr(start_index, end_index - start_index);
  414. if (!identifier.empty())
  415. {
  416. switch (identifier[0])
  417. {
  418. case '#': id = identifier.substr(1); break;
  419. case '.': classes.push_back(identifier.substr(1)); break;
  420. case ':':
  421. {
  422. String pseudo_class_name = identifier.substr(1);
  423. if (StyleSheetFactory::GetSelector(pseudo_class_name) != NULL)
  424. structural_pseudo_classes.push_back(pseudo_class_name);
  425. else
  426. pseudo_classes.push_back(pseudo_class_name);
  427. }
  428. break;
  429. default: tag = identifier;
  430. }
  431. }
  432. index = end_index;
  433. }
  434. // Sort the classes and pseudo-classes so they are consistent across equivalent declarations that shuffle the
  435. // order around.
  436. std::sort(classes.begin(), classes.end());
  437. std::sort(pseudo_classes.begin(), pseudo_classes.end());
  438. std::sort(structural_pseudo_classes.begin(), structural_pseudo_classes.end());
  439. // Get the named child node.
  440. leaf_node = leaf_node->GetChildNode(tag, StyleSheetNode::TAG);
  441. tag_node = leaf_node;
  442. if (!id.empty())
  443. leaf_node = leaf_node->GetChildNode(id, StyleSheetNode::ID);
  444. for (size_t j = 0; j < classes.size(); ++j)
  445. leaf_node = leaf_node->GetChildNode(classes[j], StyleSheetNode::CLASS);
  446. for (size_t j = 0; j < structural_pseudo_classes.size(); ++j)
  447. leaf_node = leaf_node->GetChildNode(structural_pseudo_classes[j], StyleSheetNode::STRUCTURAL_PSEUDO_CLASS);
  448. for (size_t j = 0; j < pseudo_classes.size(); ++j)
  449. leaf_node = leaf_node->GetChildNode(pseudo_classes[j], StyleSheetNode::PSEUDO_CLASS);
  450. }
  451. // Merge the new properties with those already on the leaf node.
  452. leaf_node->ImportProperties(properties, rule_specificity);
  453. return true;
  454. }
  455. char StyleSheetParser::FindToken(String& buffer, const char* tokens, bool remove_token)
  456. {
  457. buffer.clear();
  458. char character;
  459. while (ReadCharacter(character))
  460. {
  461. if (strchr(tokens, character) != NULL)
  462. {
  463. if (remove_token)
  464. parse_buffer_pos++;
  465. return character;
  466. }
  467. else
  468. {
  469. buffer += character;
  470. parse_buffer_pos++;
  471. }
  472. }
  473. return 0;
  474. }
  475. // Attempts to find the next character in the active stream.
  476. bool StyleSheetParser::ReadCharacter(char& buffer)
  477. {
  478. bool comment = false;
  479. // Continuously fill the buffer until either we run out of
  480. // stream or we find the requested token
  481. do
  482. {
  483. while (parse_buffer_pos < parse_buffer.size())
  484. {
  485. if (parse_buffer[parse_buffer_pos] == '\n')
  486. line_number++;
  487. else if (comment)
  488. {
  489. // Check for closing comment
  490. if (parse_buffer[parse_buffer_pos] == '*')
  491. {
  492. parse_buffer_pos++;
  493. if (parse_buffer_pos >= parse_buffer.size())
  494. {
  495. if (!FillBuffer())
  496. return false;
  497. }
  498. if (parse_buffer[parse_buffer_pos] == '/')
  499. comment = false;
  500. }
  501. }
  502. else
  503. {
  504. // Check for an opening comment
  505. if (parse_buffer[parse_buffer_pos] == '/')
  506. {
  507. parse_buffer_pos++;
  508. if (parse_buffer_pos >= parse_buffer.size())
  509. {
  510. if (!FillBuffer())
  511. {
  512. buffer = '/';
  513. parse_buffer = "/";
  514. return true;
  515. }
  516. }
  517. if (parse_buffer[parse_buffer_pos] == '*')
  518. comment = true;
  519. else
  520. {
  521. buffer = '/';
  522. if (parse_buffer_pos == 0)
  523. parse_buffer.insert(parse_buffer_pos, 1, '/');
  524. else
  525. parse_buffer_pos--;
  526. return true;
  527. }
  528. }
  529. if (!comment)
  530. {
  531. // If we find a character, return it
  532. buffer = parse_buffer[parse_buffer_pos];
  533. return true;
  534. }
  535. }
  536. parse_buffer_pos++;
  537. }
  538. }
  539. while (FillBuffer());
  540. return false;
  541. }
  542. // Fills the internal buffer with more content
  543. bool StyleSheetParser::FillBuffer()
  544. {
  545. // If theres no data to process, abort
  546. if (stream->IsEOS())
  547. return false;
  548. // Read in some data (4092 instead of 4096 to avoid the buffer growing when we have to add back
  549. // a character after a failed comment parse.)
  550. parse_buffer.clear();
  551. bool read = stream->Read(parse_buffer, 4092) > 0;
  552. parse_buffer_pos = 0;
  553. return read;
  554. }
  555. }
  556. }