StyleSheetParser.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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.size());
  77. for(auto& block : blocks)
  78. {
  79. for (auto& property : block.properties)
  80. property_ids.insert(property.first);
  81. }
  82. }
  83. }
  84. bool StyleSheetParser::ParseKeyframeBlock(KeyframesMap& keyframes_map, const String& identifier, const String& rules, const PropertyDictionary& properties)
  85. {
  86. if (!IsValidIdentifier(identifier))
  87. {
  88. Log::Message(Log::LT_WARNING, "Invalid keyframes identifier '%s' at %s:%d", identifier.c_str(), stream_file_name.c_str(), line_number);
  89. return false;
  90. }
  91. if (properties.size() == 0)
  92. return true;
  93. StringList rule_list;
  94. StringUtilities::ExpandString(rule_list, rules);
  95. std::vector<float> rule_values;
  96. rule_values.reserve(rule_list.size());
  97. for (auto rule : rule_list)
  98. {
  99. float value = 0.0f;
  100. int count = 0;
  101. rule = ToLower(rule);
  102. if (rule == "from")
  103. rule_values.push_back(0.0f);
  104. else if (rule == "to")
  105. rule_values.push_back(1.0f);
  106. else if(sscanf(rule.c_str(), "%f%%%n", &value, &count) == 1)
  107. if(count > 0 && value >= 0.0f && value <= 100.0f)
  108. rule_values.push_back(0.01f * value);
  109. }
  110. if (rule_values.empty())
  111. {
  112. Log::Message(Log::LT_WARNING, "Invalid keyframes rule(s) '%s' at %s:%d", rules.c_str(), stream_file_name.c_str(), line_number);
  113. return false;
  114. }
  115. Keyframes& keyframes = keyframes_map[identifier];
  116. for(float selector : rule_values)
  117. {
  118. 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; });
  119. if (it == keyframes.blocks.end())
  120. {
  121. keyframes.blocks.emplace_back( selector );
  122. it = (keyframes.blocks.end() - 1);
  123. }
  124. else
  125. {
  126. // In case of duplicate keyframes, we only use the latest definition as per CSS rules
  127. it->properties = PropertyDictionary();
  128. }
  129. Import(it->properties, properties);
  130. }
  131. return true;
  132. }
  133. int StyleSheetParser::Parse(StyleSheetNode* node, KeyframesMap& keyframes, Stream* _stream)
  134. {
  135. int rule_count = 0;
  136. line_number = 0;
  137. stream = _stream;
  138. stream_file_name = Replace(stream->GetSourceURL().GetURL(), "|", ":");
  139. enum class State { Global, KeyframesIdentifier, KeyframesRules, Invalid };
  140. State state = State::Global;
  141. String keyframes_identifier;
  142. // Look for more styles while data is available
  143. while (FillBuffer())
  144. {
  145. String pre_token_str;
  146. while (char token = FindToken(pre_token_str, "{@}", true))
  147. {
  148. switch (state)
  149. {
  150. case State::Global:
  151. {
  152. if (token == '{')
  153. {
  154. // Read the attributes
  155. PropertyDictionary properties;
  156. if (!ReadProperties(properties))
  157. continue;
  158. StringList style_name_list;
  159. StringUtilities::ExpandString(style_name_list, pre_token_str);
  160. // Add style nodes to the root of the tree
  161. for (size_t i = 0; i < style_name_list.size(); i++)
  162. ImportProperties(node, style_name_list[i], properties, rule_count);
  163. rule_count++;
  164. }
  165. else if (token == '@')
  166. {
  167. state = State::KeyframesIdentifier;
  168. }
  169. else
  170. {
  171. 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);
  172. }
  173. }
  174. break;
  175. case State::KeyframesIdentifier:
  176. {
  177. if (token == '{')
  178. {
  179. static const String& keyframes_str = GetName(PropertyId::Keyframes);
  180. keyframes_identifier.clear();
  181. if (pre_token_str.substr(0, keyframes_str.size()) == keyframes_str)
  182. {
  183. keyframes_identifier = StringUtilities::StripWhitespace(pre_token_str.substr(keyframes_str.size()));
  184. }
  185. state = State::KeyframesRules;
  186. }
  187. else
  188. {
  189. Log::Message(Log::LT_WARNING, "Invalid character '%c' found while parsing keyframes identifier in stylesheet at %s:%d", token, stream_file_name.c_str(), line_number);
  190. state = State::Invalid;
  191. }
  192. }
  193. break;
  194. case State::KeyframesRules:
  195. {
  196. if (token == '{')
  197. {
  198. state = State::KeyframesRules;
  199. PropertyDictionary properties;
  200. if (!ReadProperties(properties))
  201. continue;
  202. if (!ParseKeyframeBlock(keyframes, keyframes_identifier, pre_token_str, properties))
  203. continue;
  204. }
  205. else if (token == '}')
  206. {
  207. state = State::Global;
  208. }
  209. else
  210. {
  211. Log::Message(Log::LT_WARNING, "Invalid character '%c' found while parsing keyframes in stylesheet at %s:%d", token, stream_file_name.c_str(), line_number);
  212. state = State::Invalid;
  213. }
  214. }
  215. break;
  216. default:
  217. ROCKET_ERROR;
  218. state = State::Invalid;
  219. break;
  220. }
  221. if (state == State::Invalid)
  222. break;
  223. }
  224. if (state == State::Invalid)
  225. break;
  226. }
  227. PostprocessKeyframes(keyframes);
  228. return rule_count;
  229. }
  230. bool StyleSheetParser::ParseProperties(PropertyDictionary& parsed_properties, const String& properties)
  231. {
  232. stream = new StreamMemory((const byte*)properties.c_str(), properties.size());
  233. bool success = ReadProperties(parsed_properties);
  234. stream->RemoveReference();
  235. stream = NULL;
  236. return success;
  237. }
  238. bool StyleSheetParser::ReadProperties(PropertyDictionary& properties)
  239. {
  240. int rule_line_number = (int)line_number;
  241. String name;
  242. String value;
  243. enum ParseState { NAME, VALUE, QUOTE };
  244. ParseState state = NAME;
  245. char character;
  246. char previous_character = 0;
  247. while (ReadCharacter(character))
  248. {
  249. parse_buffer_pos++;
  250. switch (state)
  251. {
  252. case NAME:
  253. {
  254. if (character == ';')
  255. {
  256. name = StringUtilities::StripWhitespace(name);
  257. if (!name.empty())
  258. {
  259. Log::Message(Log::LT_WARNING, "Found name with no value parsing property declaration '%s' at %s:%d", name.c_str(), stream_file_name.c_str(), line_number);
  260. name.clear();
  261. }
  262. }
  263. else if (character == '}')
  264. {
  265. name = StringUtilities::StripWhitespace(name);
  266. if (!StringUtilities::StripWhitespace(name).empty())
  267. 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);
  268. return true;
  269. }
  270. else if (character == ':')
  271. {
  272. name = StringUtilities::StripWhitespace(name);
  273. state = VALUE;
  274. }
  275. else
  276. name += character;
  277. }
  278. break;
  279. case VALUE:
  280. {
  281. if (character == ';')
  282. {
  283. value = StringUtilities::StripWhitespace(value);
  284. PropertyId id = GetPropertyId(name);
  285. if (!StyleSheetSpecification::ParsePropertyDeclaration(properties, id, value, stream_file_name, rule_line_number))
  286. 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);
  287. name.clear();
  288. value.clear();
  289. state = NAME;
  290. }
  291. else if (character == '}')
  292. {
  293. 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);
  294. return true;
  295. }
  296. else
  297. {
  298. value += character;
  299. if (character == '"')
  300. state = QUOTE;
  301. }
  302. }
  303. break;
  304. case QUOTE:
  305. {
  306. value += character;
  307. if (character == '"' && previous_character != '/')
  308. state = VALUE;
  309. }
  310. break;
  311. }
  312. previous_character = character;
  313. }
  314. if (!name.empty() || !value.empty())
  315. 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);
  316. return true;
  317. }
  318. // Updates the StyleNode tree, creating new nodes as necessary, setting the definition index
  319. bool StyleSheetParser::ImportProperties(StyleSheetNode* node, const String& names, const PropertyDictionary& properties, int rule_specificity)
  320. {
  321. StyleSheetNode* tag_node = NULL;
  322. StyleSheetNode* leaf_node = node;
  323. StringList nodes;
  324. StringUtilities::ExpandString(nodes, names, ' ');
  325. // Create each node going down the tree
  326. for (size_t i = 0; i < nodes.size(); i++)
  327. {
  328. String name = nodes[i];
  329. String tag;
  330. String id;
  331. StringList classes;
  332. StringList pseudo_classes;
  333. StringList structural_pseudo_classes;
  334. size_t index = 0;
  335. while (index < name.size())
  336. {
  337. size_t start_index = index;
  338. size_t end_index = index + 1;
  339. // Read until we hit the next identifier.
  340. while (end_index < name.size() &&
  341. name[end_index] != '#' &&
  342. name[end_index] != '.' &&
  343. name[end_index] != ':')
  344. end_index++;
  345. String identifier = name.substr(start_index, end_index - start_index);
  346. if (!identifier.empty())
  347. {
  348. switch (identifier[0])
  349. {
  350. case '#': id = identifier.substr(1); break;
  351. case '.': classes.push_back(identifier.substr(1)); break;
  352. case ':':
  353. {
  354. String pseudo_class_name = identifier.substr(1);
  355. if (StyleSheetFactory::GetSelector(pseudo_class_name) != NULL)
  356. structural_pseudo_classes.push_back(pseudo_class_name);
  357. else
  358. pseudo_classes.push_back(pseudo_class_name);
  359. }
  360. break;
  361. default: tag = identifier;
  362. }
  363. }
  364. index = end_index;
  365. }
  366. // Sort the classes and pseudo-classes so they are consistent across equivalent declarations that shuffle the
  367. // order around.
  368. std::sort(classes.begin(), classes.end());
  369. std::sort(pseudo_classes.begin(), pseudo_classes.end());
  370. std::sort(structural_pseudo_classes.begin(), structural_pseudo_classes.end());
  371. // Get the named child node.
  372. leaf_node = leaf_node->GetChildNode(tag, StyleSheetNode::TAG);
  373. tag_node = leaf_node;
  374. if (!id.empty())
  375. leaf_node = leaf_node->GetChildNode(id, StyleSheetNode::ID);
  376. for (size_t j = 0; j < classes.size(); ++j)
  377. leaf_node = leaf_node->GetChildNode(classes[j], StyleSheetNode::CLASS);
  378. for (size_t j = 0; j < structural_pseudo_classes.size(); ++j)
  379. leaf_node = leaf_node->GetChildNode(structural_pseudo_classes[j], StyleSheetNode::STRUCTURAL_PSEUDO_CLASS);
  380. for (size_t j = 0; j < pseudo_classes.size(); ++j)
  381. leaf_node = leaf_node->GetChildNode(pseudo_classes[j], StyleSheetNode::PSEUDO_CLASS);
  382. }
  383. // Merge the new properties with those already on the leaf node.
  384. leaf_node->ImportProperties(properties, rule_specificity);
  385. return true;
  386. }
  387. char StyleSheetParser::FindToken(String& buffer, const char* tokens, bool remove_token)
  388. {
  389. buffer.clear();
  390. char character;
  391. while (ReadCharacter(character))
  392. {
  393. if (strchr(tokens, character) != NULL)
  394. {
  395. if (remove_token)
  396. parse_buffer_pos++;
  397. return character;
  398. }
  399. else
  400. {
  401. buffer += character;
  402. parse_buffer_pos++;
  403. }
  404. }
  405. return 0;
  406. }
  407. // Attempts to find the next character in the active stream.
  408. bool StyleSheetParser::ReadCharacter(char& buffer)
  409. {
  410. bool comment = false;
  411. // Continuously fill the buffer until either we run out of
  412. // stream or we find the requested token
  413. do
  414. {
  415. while (parse_buffer_pos < parse_buffer.size())
  416. {
  417. if (parse_buffer[parse_buffer_pos] == '\n')
  418. line_number++;
  419. else if (comment)
  420. {
  421. // Check for closing comment
  422. if (parse_buffer[parse_buffer_pos] == '*')
  423. {
  424. parse_buffer_pos++;
  425. if (parse_buffer_pos >= parse_buffer.size())
  426. {
  427. if (!FillBuffer())
  428. return false;
  429. }
  430. if (parse_buffer[parse_buffer_pos] == '/')
  431. comment = false;
  432. }
  433. }
  434. else
  435. {
  436. // Check for an opening comment
  437. if (parse_buffer[parse_buffer_pos] == '/')
  438. {
  439. parse_buffer_pos++;
  440. if (parse_buffer_pos >= parse_buffer.size())
  441. {
  442. if (!FillBuffer())
  443. {
  444. buffer = '/';
  445. parse_buffer = "/";
  446. return true;
  447. }
  448. }
  449. if (parse_buffer[parse_buffer_pos] == '*')
  450. comment = true;
  451. else
  452. {
  453. buffer = '/';
  454. if (parse_buffer_pos == 0)
  455. parse_buffer.insert(parse_buffer_pos, 1, '/');
  456. else
  457. parse_buffer_pos--;
  458. return true;
  459. }
  460. }
  461. if (!comment)
  462. {
  463. // If we find a character, return it
  464. buffer = parse_buffer[parse_buffer_pos];
  465. return true;
  466. }
  467. }
  468. parse_buffer_pos++;
  469. }
  470. }
  471. while (FillBuffer());
  472. return false;
  473. }
  474. // Fills the internal buffer with more content
  475. bool StyleSheetParser::FillBuffer()
  476. {
  477. // If theres no data to process, abort
  478. if (stream->IsEOS())
  479. return false;
  480. // Read in some data (4092 instead of 4096 to avoid the buffer growing when we have to add back
  481. // a character after a failed comment parse.)
  482. parse_buffer.clear();
  483. bool read = stream->Read(parse_buffer, 4092) > 0;
  484. parse_buffer_pos = 0;
  485. return read;
  486. }
  487. }
  488. }