StyleSheetParser.cpp 15 KB

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