StyleSheetParser.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  1. /*
  2. * This source file is part of RmlUi, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://github.com/mikke89/RmlUi
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. * Copyright (c) 2019 The RmlUi Team, and contributors
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. */
  28. #include "StyleSheetParser.h"
  29. #include "ComputeProperty.h"
  30. #include "StyleSheetFactory.h"
  31. #include "StyleSheetNode.h"
  32. #include "../../Include/RmlUi/Core/DecoratorInstancer.h"
  33. #include "../../Include/RmlUi/Core/Factory.h"
  34. #include "../../Include/RmlUi/Core/Log.h"
  35. #include "../../Include/RmlUi/Core/Profiling.h"
  36. #include "../../Include/RmlUi/Core/PropertyDefinition.h"
  37. #include "../../Include/RmlUi/Core/PropertySpecification.h"
  38. #include "../../Include/RmlUi/Core/StreamMemory.h"
  39. #include "../../Include/RmlUi/Core/StyleSheet.h"
  40. #include "../../Include/RmlUi/Core/StyleSheetContainer.h"
  41. #include "../../Include/RmlUi/Core/StyleSheetSpecification.h"
  42. #include <algorithm>
  43. #include <string.h>
  44. namespace Rml {
  45. class AbstractPropertyParser {
  46. public:
  47. virtual bool Parse(const String& name, const String& value) = 0;
  48. };
  49. /*
  50. * PropertySpecificationParser just passes the parsing to a property specification. Usually
  51. * the main stylesheet specification, except for e.g. @decorator blocks.
  52. */
  53. class PropertySpecificationParser final : public AbstractPropertyParser {
  54. private:
  55. // The dictionary to store the properties in.
  56. PropertyDictionary& properties;
  57. // The specification used to parse the values. Normally the default stylesheet specification, but not for e.g. all at-rules such as decorators.
  58. const PropertySpecification& specification;
  59. public:
  60. PropertySpecificationParser(PropertyDictionary& properties, const PropertySpecification& specification) : properties(properties), specification(specification) {}
  61. bool Parse(const String& name, const String& value) override
  62. {
  63. return specification.ParsePropertyDeclaration(properties, name, value);
  64. }
  65. };
  66. /*
  67. * Spritesheets need a special parser because its property names are arbitrary keys,
  68. * while its values are always rectangles. Thus, it must be parsed with a special "rectangle" parser
  69. * for every name-value pair. We can probably optimize this for @performance.
  70. */
  71. class SpritesheetPropertyParser final : public AbstractPropertyParser {
  72. private:
  73. String image_source;
  74. float image_resolution_factor = 1.f;
  75. SpriteDefinitionList sprite_definitions;
  76. PropertyDictionary properties;
  77. PropertySpecification specification;
  78. PropertyId id_rx, id_ry, id_rw, id_rh, id_resolution;
  79. ShorthandId id_rectangle;
  80. public:
  81. SpritesheetPropertyParser() : specification(4, 1)
  82. {
  83. id_rx = specification.RegisterProperty("rectangle-x", "", false, false).AddParser("length").GetId();
  84. id_ry = specification.RegisterProperty("rectangle-y", "", false, false).AddParser("length").GetId();
  85. id_rw = specification.RegisterProperty("rectangle-w", "", false, false).AddParser("length").GetId();
  86. id_rh = specification.RegisterProperty("rectangle-h", "", false, false).AddParser("length").GetId();
  87. id_rectangle = specification.RegisterShorthand("rectangle", "rectangle-x, rectangle-y, rectangle-w, rectangle-h", ShorthandType::FallThrough);
  88. id_resolution = specification.RegisterProperty("resolution", "", false, false).AddParser("resolution").GetId();
  89. }
  90. const String& GetImageSource() const
  91. {
  92. return image_source;
  93. }
  94. const SpriteDefinitionList& GetSpriteDefinitions() const
  95. {
  96. return sprite_definitions;
  97. }
  98. float GetImageResolutionFactor() const
  99. {
  100. return image_resolution_factor;
  101. }
  102. void Clear() {
  103. image_resolution_factor = 1.f;
  104. image_source.clear();
  105. sprite_definitions.clear();
  106. }
  107. bool Parse(const String& name, const String& value) override
  108. {
  109. if (name == "src")
  110. {
  111. image_source = value;
  112. }
  113. else if (name == "resolution")
  114. {
  115. if (!specification.ParsePropertyDeclaration(properties, id_resolution, value))
  116. return false;
  117. if (const Property* property = properties.GetProperty(id_resolution))
  118. {
  119. if (property->unit == Property::X)
  120. image_resolution_factor = property->Get<float>();
  121. }
  122. }
  123. else
  124. {
  125. if (!specification.ParseShorthandDeclaration(properties, id_rectangle, value))
  126. return false;
  127. Rectangle rectangle;
  128. if (auto property = properties.GetProperty(id_rx))
  129. rectangle.x = ComputeAbsoluteLength(*property, 1.f, Vector2f(1.f));
  130. if (auto property = properties.GetProperty(id_ry))
  131. rectangle.y = ComputeAbsoluteLength(*property, 1.f, Vector2f(1.f));
  132. if (auto property = properties.GetProperty(id_rw))
  133. rectangle.width = ComputeAbsoluteLength(*property, 1.f, Vector2f(1.f));
  134. if (auto property = properties.GetProperty(id_rh))
  135. rectangle.height = ComputeAbsoluteLength(*property, 1.f, Vector2f(1.f));
  136. sprite_definitions.emplace_back(name, rectangle);
  137. }
  138. return true;
  139. }
  140. };
  141. static UniquePtr<SpritesheetPropertyParser> spritesheet_property_parser;
  142. /*
  143. * Media queries need a special parser because they have unique properties that
  144. * aren't admissible in other property declaration contexts and the syntax of
  145. */
  146. class MediaQueryPropertyParser final : public AbstractPropertyParser {
  147. private:
  148. // The dictionary to store the properties in.
  149. PropertyDictionary* properties;
  150. PropertySpecification specification;
  151. static inline PropertyId CastId(MediaQueryId id)
  152. {
  153. return static_cast<PropertyId>(id);
  154. }
  155. public:
  156. MediaQueryPropertyParser() : specification(14, 0)
  157. {
  158. specification.RegisterProperty("width", "", false, false, CastId(MediaQueryId::Width)).AddParser("length");
  159. specification.RegisterProperty("min-width", "", false, false, CastId(MediaQueryId::MinWidth)).AddParser("length");
  160. specification.RegisterProperty("max-width", "", false, false, CastId(MediaQueryId::MaxWidth)).AddParser("length");
  161. specification.RegisterProperty("height", "", false, false, CastId(MediaQueryId::Height)).AddParser("length");
  162. specification.RegisterProperty("min-height", "", false, false, CastId(MediaQueryId::MinHeight)).AddParser("length");
  163. specification.RegisterProperty("max-height", "", false, false, CastId(MediaQueryId::MaxHeight)).AddParser("length");
  164. specification.RegisterProperty("aspect-ratio", "", false, false, CastId(MediaQueryId::AspectRatio)).AddParser("ratio");
  165. specification.RegisterProperty("min-aspect-ratio", "", false, false, CastId(MediaQueryId::MinAspectRatio)).AddParser("ratio");
  166. specification.RegisterProperty("max-aspect-ratio", "", false, false, CastId(MediaQueryId::MaxAspectRatio)).AddParser("ratio");
  167. specification.RegisterProperty("resolution", "", false, false, CastId(MediaQueryId::Resolution)).AddParser("resolution");
  168. specification.RegisterProperty("min-resolution", "", false, false, CastId(MediaQueryId::MinResolution)).AddParser("resolution");
  169. specification.RegisterProperty("max-resolution", "", false, false, CastId(MediaQueryId::MaxResolution)).AddParser("resolution");
  170. specification.RegisterProperty("orientation", "", false, false, CastId(MediaQueryId::Orientation)).AddParser("keyword", "landscape, portrait");
  171. }
  172. void SetTargetProperties(PropertyDictionary* _properties)
  173. {
  174. properties = _properties;
  175. }
  176. void Clear() {
  177. properties = nullptr;
  178. }
  179. bool Parse(const String& name, const String& value) override
  180. {
  181. RMLUI_ASSERT(properties);
  182. return specification.ParsePropertyDeclaration(*properties, name, value);
  183. }
  184. };
  185. static UniquePtr<MediaQueryPropertyParser> media_query_property_parser;
  186. StyleSheetParser::StyleSheetParser()
  187. {
  188. line_number = 0;
  189. stream = nullptr;
  190. parse_buffer_pos = 0;
  191. }
  192. StyleSheetParser::~StyleSheetParser()
  193. {
  194. }
  195. void StyleSheetParser::Initialise()
  196. {
  197. spritesheet_property_parser = MakeUnique<SpritesheetPropertyParser>();
  198. media_query_property_parser = MakeUnique<MediaQueryPropertyParser>();
  199. }
  200. void StyleSheetParser::Shutdown()
  201. {
  202. spritesheet_property_parser.reset();
  203. media_query_property_parser.reset();
  204. }
  205. static bool IsValidIdentifier(const String& str)
  206. {
  207. if (str.empty())
  208. return false;
  209. for (size_t i = 0; i < str.size(); i++)
  210. {
  211. char c = str[i];
  212. bool valid = (
  213. (c >= 'a' && c <= 'z')
  214. || (c >= 'A' && c <= 'Z')
  215. || (c >= '0' && c <= '9')
  216. || (c == '-')
  217. || (c == '_')
  218. );
  219. if (!valid)
  220. return false;
  221. }
  222. return true;
  223. }
  224. static void PostprocessKeyframes(KeyframesMap& keyframes_map)
  225. {
  226. for (auto& keyframes_pair : keyframes_map)
  227. {
  228. Keyframes& keyframes = keyframes_pair.second;
  229. auto& blocks = keyframes.blocks;
  230. auto& property_ids = keyframes.property_ids;
  231. // Sort keyframes on selector value.
  232. std::sort(blocks.begin(), blocks.end(), [](const KeyframeBlock& a, const KeyframeBlock& b) { return a.normalized_time < b.normalized_time; });
  233. // Add all property names specified by any block
  234. if(blocks.size() > 0) property_ids.reserve(blocks.size() * blocks[0].properties.GetNumProperties());
  235. for(auto& block : blocks)
  236. {
  237. for (auto& property : block.properties.GetProperties())
  238. property_ids.push_back(property.first);
  239. }
  240. // Remove duplicate property names
  241. std::sort(property_ids.begin(), property_ids.end());
  242. property_ids.erase(std::unique(property_ids.begin(), property_ids.end()), property_ids.end());
  243. property_ids.shrink_to_fit();
  244. }
  245. }
  246. bool StyleSheetParser::ParseKeyframeBlock(KeyframesMap& keyframes_map, const String& identifier, const String& rules, const PropertyDictionary& properties)
  247. {
  248. if (!IsValidIdentifier(identifier))
  249. {
  250. Log::Message(Log::LT_WARNING, "Invalid keyframes identifier '%s' at %s:%d", identifier.c_str(), stream_file_name.c_str(), line_number);
  251. return false;
  252. }
  253. if (properties.GetNumProperties() == 0)
  254. return true;
  255. StringList rule_list;
  256. StringUtilities::ExpandString(rule_list, rules);
  257. Vector<float> rule_values;
  258. rule_values.reserve(rule_list.size());
  259. for (auto rule : rule_list)
  260. {
  261. float value = 0.0f;
  262. int count = 0;
  263. rule = StringUtilities::ToLower(rule);
  264. if (rule == "from")
  265. rule_values.push_back(0.0f);
  266. else if (rule == "to")
  267. rule_values.push_back(1.0f);
  268. else if(sscanf(rule.c_str(), "%f%%%n", &value, &count) == 1)
  269. if(count > 0 && value >= 0.0f && value <= 100.0f)
  270. rule_values.push_back(0.01f * value);
  271. }
  272. if (rule_values.empty())
  273. {
  274. Log::Message(Log::LT_WARNING, "Invalid keyframes rule(s) '%s' at %s:%d", rules.c_str(), stream_file_name.c_str(), line_number);
  275. return false;
  276. }
  277. Keyframes& keyframes = keyframes_map[identifier];
  278. for(float selector : rule_values)
  279. {
  280. 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; });
  281. if (it == keyframes.blocks.end())
  282. {
  283. keyframes.blocks.emplace_back(selector);
  284. it = (keyframes.blocks.end() - 1);
  285. }
  286. else
  287. {
  288. // In case of duplicate keyframes, we only use the latest definition as per CSS rules
  289. it->properties = PropertyDictionary();
  290. }
  291. it->properties.Import(properties);
  292. }
  293. return true;
  294. }
  295. bool StyleSheetParser::ParseDecoratorBlock(const String& at_name, DecoratorSpecificationMap& decorator_map, const StyleSheet& style_sheet, const SharedPtr<const PropertySource>& source)
  296. {
  297. StringList name_type;
  298. StringUtilities::ExpandString(name_type, at_name, ':');
  299. if (name_type.size() != 2 || name_type[0].empty() || name_type[1].empty())
  300. {
  301. Log::Message(Log::LT_WARNING, "Decorator syntax error at %s:%d. Use syntax: '@decorator name : type { ... }'.", stream_file_name.c_str(), line_number);
  302. return false;
  303. }
  304. const String& name = name_type[0];
  305. String decorator_type = name_type[1];
  306. auto it_find = decorator_map.find(name);
  307. if (it_find != decorator_map.end())
  308. {
  309. 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);
  310. return false;
  311. }
  312. // Get the instancer associated with the decorator type
  313. DecoratorInstancer* decorator_instancer = Factory::GetDecoratorInstancer(decorator_type);
  314. PropertyDictionary properties;
  315. if(!decorator_instancer)
  316. {
  317. // Type is not a declared decorator type, instead, see if it is another decorator name, then we inherit its properties.
  318. auto it = decorator_map.find(decorator_type);
  319. if (it != decorator_map.end())
  320. {
  321. // Yes, try to retrieve the instancer from the parent type, and add its property values.
  322. decorator_instancer = Factory::GetDecoratorInstancer(it->second.decorator_type);
  323. properties = it->second.properties;
  324. decorator_type = it->second.decorator_type;
  325. }
  326. // If we still don't have an instancer, we cannot continue.
  327. if (!decorator_instancer)
  328. {
  329. Log::Message(Log::LT_WARNING, "Invalid decorator type '%s' declared at %s:%d.", decorator_type.c_str(), stream_file_name.c_str(), line_number);
  330. return false;
  331. }
  332. }
  333. const PropertySpecification& property_specification = decorator_instancer->GetPropertySpecification();
  334. PropertySpecificationParser parser(properties, property_specification);
  335. if (!ReadProperties(parser))
  336. return false;
  337. // Set non-defined properties to their defaults
  338. property_specification.SetPropertyDefaults(properties);
  339. properties.SetSourceOfAllProperties(source);
  340. SharedPtr<Decorator> decorator = decorator_instancer->InstanceDecorator(decorator_type, properties, DecoratorInstancerInterface(style_sheet));
  341. if (!decorator)
  342. {
  343. 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);
  344. return false;
  345. }
  346. decorator_map.emplace(name, DecoratorSpecification{ std::move(decorator_type), std::move(properties), std::move(decorator) });
  347. return true;
  348. }
  349. bool StyleSheetParser::ParseMediaFeatureMap(PropertyDictionary& properties, const String & rules)
  350. {
  351. media_query_property_parser->SetTargetProperties(&properties);
  352. enum ParseState { Global, Name, Value };
  353. ParseState state = Name;
  354. char character = 0;
  355. size_t cursor = 0;
  356. String name;
  357. String current_string;
  358. while(cursor++ < rules.length())
  359. {
  360. character = rules[cursor];
  361. switch(character)
  362. {
  363. case '(':
  364. {
  365. if (state != Global)
  366. {
  367. Log::Message(Log::LT_WARNING, "Unexpected '(' in @media query list at %s:%d.", stream_file_name.c_str(), line_number);
  368. return false;
  369. }
  370. current_string = StringUtilities::StripWhitespace(StringUtilities::ToLower(current_string));
  371. if (current_string != "and")
  372. {
  373. Log::Message(Log::LT_WARNING, "Unexpected '%s' in @media query list at %s:%d. Expected 'and'.", current_string.c_str(), stream_file_name.c_str(), line_number);
  374. return false;
  375. }
  376. current_string.clear();
  377. state = Name;
  378. }
  379. break;
  380. case ')':
  381. {
  382. if (state != Value)
  383. {
  384. Log::Message(Log::LT_WARNING, "Unexpected ')' in @media query list at %s:%d.", stream_file_name.c_str(), line_number);
  385. return false;
  386. }
  387. current_string = StringUtilities::StripWhitespace(current_string);
  388. if(!media_query_property_parser->Parse(name, current_string))
  389. Log::Message(Log::LT_WARNING, "Syntax error parsing media-query property declaration '%s: %s;' in %s: %d.", name.c_str(), current_string.c_str(), stream_file_name.c_str(), line_number);
  390. current_string.clear();
  391. state = Global;
  392. }
  393. break;
  394. case ':':
  395. {
  396. if (state != Name)
  397. {
  398. Log::Message(Log::LT_WARNING, "Unexpected ':' in @media query list at %s:%d.", stream_file_name.c_str(), line_number);
  399. return false;
  400. }
  401. current_string = StringUtilities::StripWhitespace(StringUtilities::ToLower(current_string));
  402. if (!IsValidIdentifier(current_string))
  403. {
  404. Log::Message(Log::LT_WARNING, "Malformed property name '%s' in @media query list at %s:%d.", current_string.c_str(), stream_file_name.c_str(), line_number);
  405. return false;
  406. }
  407. name = current_string;
  408. current_string.clear();
  409. state = Value;
  410. }
  411. break;
  412. default:
  413. current_string += character;
  414. }
  415. }
  416. if (properties.GetNumProperties() == 0)
  417. {
  418. Log::Message(Log::LT_WARNING, "Media query list parsing yielded no properties at %s:%d.", stream_file_name.c_str(), line_number);
  419. }
  420. return true;
  421. }
  422. int StyleSheetParser::Parse(MediaBlockList& style_sheets, Stream* _stream, int begin_line_number)
  423. {
  424. RMLUI_ZoneScoped;
  425. int rule_count = 0;
  426. line_number = begin_line_number;
  427. stream = _stream;
  428. stream_file_name = StringUtilities::Replace(stream->GetSourceURL().GetURL(), '|', ':');
  429. enum class State { Global, AtRuleIdentifier, KeyframeBlock, Invalid };
  430. State state = State::Global;
  431. MediaBlock current_block = {};
  432. // Need to track whether currently inside a nested media block or not, since the default scope is also a media block
  433. bool inside_media_block = false;
  434. // At-rules given by the following syntax in global space: @identifier name { block }
  435. String at_rule_name;
  436. // Look for more styles while data is available
  437. while (FillBuffer())
  438. {
  439. String pre_token_str;
  440. while (char token = FindToken(pre_token_str, "{@}", true))
  441. {
  442. switch (state)
  443. {
  444. case State::Global:
  445. {
  446. if (token == '{')
  447. {
  448. // Initialize current block if not present
  449. if (!current_block.stylesheet)
  450. {
  451. current_block = MediaBlock{PropertyDictionary{}, UniquePtr<StyleSheet>(new StyleSheet())};
  452. }
  453. const int rule_line_number = (int)line_number;
  454. // Read the attributes
  455. PropertyDictionary properties;
  456. PropertySpecificationParser parser(properties, StyleSheetSpecification::GetPropertySpecification());
  457. if (!ReadProperties(parser))
  458. continue;
  459. StringList rule_name_list;
  460. StringUtilities::ExpandString(rule_name_list, pre_token_str);
  461. // Add style nodes to the root of the tree
  462. for (size_t i = 0; i < rule_name_list.size(); i++)
  463. {
  464. auto source = MakeShared<PropertySource>(stream_file_name, rule_line_number, rule_name_list[i]);
  465. properties.SetSourceOfAllProperties(source);
  466. ImportProperties(current_block.stylesheet->root.get(), rule_name_list[i], properties, rule_count);
  467. }
  468. rule_count++;
  469. }
  470. else if (token == '@')
  471. {
  472. state = State::AtRuleIdentifier;
  473. }
  474. else if (inside_media_block && token == '}')
  475. {
  476. // Complete current block
  477. PostprocessKeyframes(current_block.stylesheet->keyframes);
  478. current_block.stylesheet->specificity_offset = rule_count;
  479. style_sheets.push_back(std::move(current_block));
  480. current_block = {};
  481. inside_media_block = false;
  482. break;
  483. }
  484. else
  485. {
  486. 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);
  487. }
  488. }
  489. break;
  490. case State::AtRuleIdentifier:
  491. {
  492. if (token == '{')
  493. {
  494. // Initialize current block if not present
  495. if (!current_block.stylesheet)
  496. {
  497. current_block = {PropertyDictionary{}, UniquePtr<StyleSheet>(new StyleSheet())};
  498. }
  499. String at_rule_identifier = pre_token_str.substr(0, pre_token_str.find(' '));
  500. at_rule_name = StringUtilities::StripWhitespace(pre_token_str.substr(at_rule_identifier.size()));
  501. if (at_rule_identifier == "keyframes")
  502. {
  503. state = State::KeyframeBlock;
  504. }
  505. else if (at_rule_identifier == "decorator")
  506. {
  507. auto source = MakeShared<PropertySource>(stream_file_name, (int)line_number, pre_token_str);
  508. ParseDecoratorBlock(at_rule_name, current_block.stylesheet->decorator_map, *current_block.stylesheet, source);
  509. at_rule_name.clear();
  510. state = State::Global;
  511. }
  512. else if (at_rule_identifier == "spritesheet")
  513. {
  514. // The spritesheet parser is reasonably heavy to initialize, so we make it a static global.
  515. ReadProperties(*spritesheet_property_parser);
  516. const String& image_source = spritesheet_property_parser->GetImageSource();
  517. const SpriteDefinitionList& sprite_definitions = spritesheet_property_parser->GetSpriteDefinitions();
  518. const float image_resolution_factor = spritesheet_property_parser->GetImageResolutionFactor();
  519. if (at_rule_name.empty())
  520. {
  521. Log::Message(Log::LT_WARNING, "No name given for @spritesheet at %s:%d", stream_file_name.c_str(), line_number);
  522. }
  523. else if (sprite_definitions.empty())
  524. {
  525. Log::Message(Log::LT_WARNING, "Spritesheet with name '%s' has no sprites defined, ignored. At %s:%d", at_rule_name.c_str(), stream_file_name.c_str(), line_number);
  526. }
  527. else if (image_source.empty())
  528. {
  529. 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);
  530. }
  531. else if (image_resolution_factor <= 0.0f || image_resolution_factor >= 100.f)
  532. {
  533. Log::Message(Log::LT_WARNING, "Spritesheet resolution (property 'resolution') value must be larger than 0.0 and smaller than 100.0, given %g. In spritesheet '%s'. At %s:%d", image_resolution_factor, at_rule_name.c_str(), stream_file_name.c_str(), line_number);
  534. }
  535. else
  536. {
  537. const float display_scale = 1.0f / image_resolution_factor;
  538. current_block.stylesheet->spritesheet_list.AddSpriteSheet(at_rule_name, image_source, stream_file_name, (int)line_number, display_scale, sprite_definitions);
  539. }
  540. spritesheet_property_parser->Clear();
  541. at_rule_name.clear();
  542. state = State::Global;
  543. }
  544. else if (at_rule_identifier == "media")
  545. {
  546. // complete the current "global" block if present and start a new block
  547. if (current_block.stylesheet)
  548. {
  549. PostprocessKeyframes(current_block.stylesheet->keyframes);
  550. current_block.stylesheet->specificity_offset = rule_count;
  551. style_sheets.push_back(std::move(current_block));
  552. current_block = {};
  553. }
  554. // parse media query list into block
  555. PropertyDictionary feature_map;
  556. ParseMediaFeatureMap(feature_map, at_rule_name);
  557. current_block = {std::move(feature_map), UniquePtr<StyleSheet>(new StyleSheet())};
  558. inside_media_block = true;
  559. state = State::Global;
  560. }
  561. else
  562. {
  563. // Invalid identifier, should ignore
  564. at_rule_name.clear();
  565. state = State::Global;
  566. 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);
  567. }
  568. }
  569. else
  570. {
  571. 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);
  572. state = State::Invalid;
  573. }
  574. }
  575. break;
  576. case State::KeyframeBlock:
  577. {
  578. if (token == '{')
  579. {
  580. // Initialize current block if not present
  581. if (!current_block.stylesheet)
  582. {
  583. current_block = {PropertyDictionary{}, UniquePtr<StyleSheet>(new StyleSheet())};
  584. }
  585. // Each keyframe in keyframes has its own block which is processed here
  586. PropertyDictionary properties;
  587. PropertySpecificationParser parser(properties, StyleSheetSpecification::GetPropertySpecification());
  588. if(!ReadProperties(parser))
  589. continue;
  590. if (!ParseKeyframeBlock(current_block.stylesheet->keyframes, at_rule_name, pre_token_str, properties))
  591. continue;
  592. }
  593. else if (token == '}')
  594. {
  595. at_rule_name.clear();
  596. state = State::Global;
  597. }
  598. else
  599. {
  600. 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);
  601. state = State::Invalid;
  602. }
  603. }
  604. break;
  605. default:
  606. RMLUI_ERROR;
  607. state = State::Invalid;
  608. break;
  609. }
  610. if (state == State::Invalid)
  611. break;
  612. }
  613. if (state == State::Invalid)
  614. break;
  615. }
  616. // Complete last block if present
  617. if (current_block.stylesheet)
  618. {
  619. PostprocessKeyframes(current_block.stylesheet->keyframes);
  620. current_block.stylesheet->specificity_offset = rule_count;
  621. style_sheets.push_back(std::move(current_block));
  622. }
  623. return rule_count;
  624. }
  625. bool StyleSheetParser::ParseProperties(PropertyDictionary& parsed_properties, const String& properties)
  626. {
  627. RMLUI_ASSERT(!stream);
  628. StreamMemory stream_owner((const byte*)properties.c_str(), properties.size());
  629. stream = &stream_owner;
  630. PropertySpecificationParser parser(parsed_properties, StyleSheetSpecification::GetPropertySpecification());
  631. bool success = ReadProperties(parser);
  632. stream = nullptr;
  633. return success;
  634. }
  635. StyleSheetNodeListRaw StyleSheetParser::ConstructNodes(StyleSheetNode& root_node, const String& selectors)
  636. {
  637. const PropertyDictionary empty_properties;
  638. StringList selector_list;
  639. StringUtilities::ExpandString(selector_list, selectors);
  640. StyleSheetNodeListRaw leaf_nodes;
  641. for (const String& selector : selector_list)
  642. {
  643. StyleSheetNode* leaf_node = ImportProperties(&root_node, selector, empty_properties, 0);
  644. if (leaf_node != &root_node)
  645. leaf_nodes.push_back(leaf_node);
  646. }
  647. return leaf_nodes;
  648. }
  649. bool StyleSheetParser::ReadProperties(AbstractPropertyParser& property_parser)
  650. {
  651. RMLUI_ZoneScoped;
  652. String name;
  653. String value;
  654. enum ParseState { NAME, VALUE, QUOTE };
  655. ParseState state = NAME;
  656. char character;
  657. char previous_character = 0;
  658. while (ReadCharacter(character))
  659. {
  660. parse_buffer_pos++;
  661. switch (state)
  662. {
  663. case NAME:
  664. {
  665. if (character == ';')
  666. {
  667. name = StringUtilities::StripWhitespace(name);
  668. if (!name.empty())
  669. {
  670. 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);
  671. name.clear();
  672. }
  673. }
  674. else if (character == '}')
  675. {
  676. name = StringUtilities::StripWhitespace(name);
  677. if (!name.empty())
  678. 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);
  679. return true;
  680. }
  681. else if (character == ':')
  682. {
  683. name = StringUtilities::StripWhitespace(name);
  684. state = VALUE;
  685. }
  686. else
  687. name += character;
  688. }
  689. break;
  690. case VALUE:
  691. {
  692. if (character == ';')
  693. {
  694. value = StringUtilities::StripWhitespace(value);
  695. if (!property_parser.Parse(name, value))
  696. 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);
  697. name.clear();
  698. value.clear();
  699. state = NAME;
  700. }
  701. else if (character == '}')
  702. {
  703. break;
  704. }
  705. else
  706. {
  707. value += character;
  708. if (character == '"')
  709. state = QUOTE;
  710. }
  711. }
  712. break;
  713. case QUOTE:
  714. {
  715. value += character;
  716. if (character == '"' && previous_character != '/')
  717. state = VALUE;
  718. }
  719. break;
  720. }
  721. if (character == '}')
  722. break;
  723. previous_character = character;
  724. }
  725. if (state == VALUE && !name.empty() && !value.empty())
  726. {
  727. value = StringUtilities::StripWhitespace(value);
  728. if (!property_parser.Parse(name, value))
  729. 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);
  730. }
  731. else if (!name.empty() || !value.empty())
  732. {
  733. 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);
  734. }
  735. return true;
  736. }
  737. StyleSheetNode* StyleSheetParser::ImportProperties(StyleSheetNode* node, String rule_name, const PropertyDictionary& properties, int rule_specificity)
  738. {
  739. StyleSheetNode* leaf_node = node;
  740. StringList nodes;
  741. // Find child combinators, the RCSS '>' rule.
  742. size_t i_child = rule_name.find('>');
  743. while (i_child != String::npos)
  744. {
  745. // So we found one! Next, we want to format the rule such that the '>' is located at the
  746. // end of the left-hand-side node, and that there is a space to the right-hand-side. This ensures that
  747. // the selector is applied to the "parent", and that parent and child are expanded properly below.
  748. size_t i_begin = i_child;
  749. while (i_begin > 0 && rule_name[i_begin - 1] == ' ')
  750. i_begin--;
  751. const size_t i_end = i_child + 1;
  752. rule_name.replace(i_begin, i_end - i_begin, "> ");
  753. i_child = rule_name.find('>', i_begin + 1);
  754. }
  755. // Expand each individual node separated by spaces. Don't expand inside parenthesis because of structural selectors.
  756. StringUtilities::ExpandString(nodes, rule_name, ' ', '(', ')', true);
  757. // Create each node going down the tree
  758. for (size_t i = 0; i < nodes.size(); i++)
  759. {
  760. const String& name = nodes[i];
  761. String tag;
  762. String id;
  763. StringList classes;
  764. StringList pseudo_classes;
  765. StructuralSelectorList structural_pseudo_classes;
  766. bool child_combinator = false;
  767. size_t index = 0;
  768. while (index < name.size())
  769. {
  770. size_t start_index = index;
  771. size_t end_index = index + 1;
  772. // Read until we hit the next identifier.
  773. while (end_index < name.size() &&
  774. name[end_index] != '#' &&
  775. name[end_index] != '.' &&
  776. name[end_index] != ':' &&
  777. name[end_index] != '>')
  778. end_index++;
  779. String identifier = name.substr(start_index, end_index - start_index);
  780. if (!identifier.empty())
  781. {
  782. switch (identifier[0])
  783. {
  784. case '#': id = identifier.substr(1); break;
  785. case '.': classes.push_back(identifier.substr(1)); break;
  786. case ':':
  787. {
  788. String pseudo_class_name = identifier.substr(1);
  789. StructuralSelector node_selector = StyleSheetFactory::GetSelector(pseudo_class_name);
  790. if (node_selector.selector)
  791. structural_pseudo_classes.push_back(node_selector);
  792. else
  793. pseudo_classes.push_back(pseudo_class_name);
  794. }
  795. break;
  796. case '>': child_combinator = true; break;
  797. default: if(identifier != "*") tag = identifier;
  798. }
  799. }
  800. index = end_index;
  801. }
  802. // Sort the classes and pseudo-classes so they are consistent across equivalent declarations that shuffle the order around.
  803. std::sort(classes.begin(), classes.end());
  804. std::sort(pseudo_classes.begin(), pseudo_classes.end());
  805. std::sort(structural_pseudo_classes.begin(), structural_pseudo_classes.end());
  806. // Get the named child node.
  807. leaf_node = leaf_node->GetOrCreateChildNode(std::move(tag), std::move(id), std::move(classes), std::move(pseudo_classes), std::move(structural_pseudo_classes), child_combinator);
  808. }
  809. // Merge the new properties with those already on the leaf node.
  810. leaf_node->ImportProperties(properties, rule_specificity);
  811. return leaf_node;
  812. }
  813. char StyleSheetParser::FindToken(String& buffer, const char* tokens, bool remove_token)
  814. {
  815. buffer.clear();
  816. char character;
  817. while (ReadCharacter(character))
  818. {
  819. if (strchr(tokens, character) != nullptr)
  820. {
  821. if (remove_token)
  822. parse_buffer_pos++;
  823. return character;
  824. }
  825. else
  826. {
  827. buffer += character;
  828. parse_buffer_pos++;
  829. }
  830. }
  831. return 0;
  832. }
  833. // Attempts to find the next character in the active stream.
  834. bool StyleSheetParser::ReadCharacter(char& buffer)
  835. {
  836. bool comment = false;
  837. // Continuously fill the buffer until either we run out of
  838. // stream or we find the requested token
  839. do
  840. {
  841. while (parse_buffer_pos < parse_buffer.size())
  842. {
  843. if (parse_buffer[parse_buffer_pos] == '\n')
  844. line_number++;
  845. else if (comment)
  846. {
  847. // Check for closing comment
  848. if (parse_buffer[parse_buffer_pos] == '*')
  849. {
  850. parse_buffer_pos++;
  851. if (parse_buffer_pos >= parse_buffer.size())
  852. {
  853. if (!FillBuffer())
  854. return false;
  855. }
  856. if (parse_buffer[parse_buffer_pos] == '/')
  857. comment = false;
  858. }
  859. }
  860. else
  861. {
  862. // Check for an opening comment
  863. if (parse_buffer[parse_buffer_pos] == '/')
  864. {
  865. parse_buffer_pos++;
  866. if (parse_buffer_pos >= parse_buffer.size())
  867. {
  868. if (!FillBuffer())
  869. {
  870. buffer = '/';
  871. parse_buffer = "/";
  872. return true;
  873. }
  874. }
  875. if (parse_buffer[parse_buffer_pos] == '*')
  876. comment = true;
  877. else
  878. {
  879. buffer = '/';
  880. if (parse_buffer_pos == 0)
  881. parse_buffer.insert(parse_buffer_pos, 1, '/');
  882. else
  883. parse_buffer_pos--;
  884. return true;
  885. }
  886. }
  887. if (!comment)
  888. {
  889. // If we find a character, return it
  890. buffer = parse_buffer[parse_buffer_pos];
  891. return true;
  892. }
  893. }
  894. parse_buffer_pos++;
  895. }
  896. }
  897. while (FillBuffer());
  898. return false;
  899. }
  900. // Fills the internal buffer with more content
  901. bool StyleSheetParser::FillBuffer()
  902. {
  903. // If theres no data to process, abort
  904. if (stream->IsEOS())
  905. return false;
  906. // Read in some data (4092 instead of 4096 to avoid the buffer growing when we have to add back
  907. // a character after a failed comment parse.)
  908. parse_buffer.clear();
  909. bool read = stream->Read(parse_buffer, 4092) > 0;
  910. parse_buffer_pos = 0;
  911. return read;
  912. }
  913. } // namespace Rml