StyleSheetParser.cpp 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133
  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. specification.RegisterProperty("theme", "", false, false, CastId(MediaQueryId::Theme)).AddParser("string");
  172. }
  173. void SetTargetProperties(PropertyDictionary* _properties)
  174. {
  175. properties = _properties;
  176. }
  177. void Clear() {
  178. properties = nullptr;
  179. }
  180. bool Parse(const String& name, const String& value) override
  181. {
  182. RMLUI_ASSERT(properties);
  183. return specification.ParsePropertyDeclaration(*properties, name, value);
  184. }
  185. };
  186. static UniquePtr<MediaQueryPropertyParser> media_query_property_parser;
  187. StyleSheetParser::StyleSheetParser()
  188. {
  189. line_number = 0;
  190. stream = nullptr;
  191. parse_buffer_pos = 0;
  192. }
  193. StyleSheetParser::~StyleSheetParser()
  194. {
  195. }
  196. void StyleSheetParser::Initialise()
  197. {
  198. spritesheet_property_parser = MakeUnique<SpritesheetPropertyParser>();
  199. media_query_property_parser = MakeUnique<MediaQueryPropertyParser>();
  200. }
  201. void StyleSheetParser::Shutdown()
  202. {
  203. spritesheet_property_parser.reset();
  204. media_query_property_parser.reset();
  205. }
  206. static bool IsValidIdentifier(const String& str)
  207. {
  208. if (str.empty())
  209. return false;
  210. for (size_t i = 0; i < str.size(); i++)
  211. {
  212. char c = str[i];
  213. bool valid = (
  214. (c >= 'a' && c <= 'z')
  215. || (c >= 'A' && c <= 'Z')
  216. || (c >= '0' && c <= '9')
  217. || (c == '-')
  218. || (c == '_')
  219. );
  220. if (!valid)
  221. return false;
  222. }
  223. return true;
  224. }
  225. static void PostprocessKeyframes(KeyframesMap& keyframes_map)
  226. {
  227. for (auto& keyframes_pair : keyframes_map)
  228. {
  229. Keyframes& keyframes = keyframes_pair.second;
  230. auto& blocks = keyframes.blocks;
  231. auto& property_ids = keyframes.property_ids;
  232. // Sort keyframes on selector value.
  233. std::sort(blocks.begin(), blocks.end(), [](const KeyframeBlock& a, const KeyframeBlock& b) { return a.normalized_time < b.normalized_time; });
  234. // Add all property names specified by any block
  235. if(blocks.size() > 0) property_ids.reserve(blocks.size() * blocks[0].properties.GetNumProperties());
  236. for(auto& block : blocks)
  237. {
  238. for (auto& property : block.properties.GetProperties())
  239. property_ids.push_back(property.first);
  240. }
  241. // Remove duplicate property names
  242. std::sort(property_ids.begin(), property_ids.end());
  243. property_ids.erase(std::unique(property_ids.begin(), property_ids.end()), property_ids.end());
  244. property_ids.shrink_to_fit();
  245. }
  246. }
  247. bool StyleSheetParser::ParseKeyframeBlock(KeyframesMap& keyframes_map, const String& identifier, const String& rules, const PropertyDictionary& properties)
  248. {
  249. if (!IsValidIdentifier(identifier))
  250. {
  251. Log::Message(Log::LT_WARNING, "Invalid keyframes identifier '%s' at %s:%d", identifier.c_str(), stream_file_name.c_str(), line_number);
  252. return false;
  253. }
  254. if (properties.GetNumProperties() == 0)
  255. return true;
  256. StringList rule_list;
  257. StringUtilities::ExpandString(rule_list, rules);
  258. Vector<float> rule_values;
  259. rule_values.reserve(rule_list.size());
  260. for (auto rule : rule_list)
  261. {
  262. float value = 0.0f;
  263. int count = 0;
  264. rule = StringUtilities::ToLower(rule);
  265. if (rule == "from")
  266. rule_values.push_back(0.0f);
  267. else if (rule == "to")
  268. rule_values.push_back(1.0f);
  269. else if(sscanf(rule.c_str(), "%f%%%n", &value, &count) == 1)
  270. if(count > 0 && value >= 0.0f && value <= 100.0f)
  271. rule_values.push_back(0.01f * value);
  272. }
  273. if (rule_values.empty())
  274. {
  275. Log::Message(Log::LT_WARNING, "Invalid keyframes rule(s) '%s' at %s:%d", rules.c_str(), stream_file_name.c_str(), line_number);
  276. return false;
  277. }
  278. Keyframes& keyframes = keyframes_map[identifier];
  279. for(float selector : rule_values)
  280. {
  281. 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; });
  282. if (it == keyframes.blocks.end())
  283. {
  284. keyframes.blocks.emplace_back(selector);
  285. it = (keyframes.blocks.end() - 1);
  286. }
  287. else
  288. {
  289. // In case of duplicate keyframes, we only use the latest definition as per CSS rules
  290. it->properties = PropertyDictionary();
  291. }
  292. it->properties.Import(properties);
  293. }
  294. return true;
  295. }
  296. bool StyleSheetParser::ParseDecoratorBlock(const String& at_name, DecoratorSpecificationMap& decorator_map, const StyleSheet& style_sheet, const SharedPtr<const PropertySource>& source)
  297. {
  298. StringList name_type;
  299. StringUtilities::ExpandString(name_type, at_name, ':');
  300. if (name_type.size() != 2 || name_type[0].empty() || name_type[1].empty())
  301. {
  302. Log::Message(Log::LT_WARNING, "Decorator syntax error at %s:%d. Use syntax: '@decorator name : type { ... }'.", stream_file_name.c_str(), line_number);
  303. return false;
  304. }
  305. const String& name = name_type[0];
  306. String decorator_type = name_type[1];
  307. auto it_find = decorator_map.find(name);
  308. if (it_find != decorator_map.end())
  309. {
  310. 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);
  311. return false;
  312. }
  313. // Get the instancer associated with the decorator type
  314. DecoratorInstancer* decorator_instancer = Factory::GetDecoratorInstancer(decorator_type);
  315. PropertyDictionary properties;
  316. if(!decorator_instancer)
  317. {
  318. // Type is not a declared decorator type, instead, see if it is another decorator name, then we inherit its properties.
  319. auto it = decorator_map.find(decorator_type);
  320. if (it != decorator_map.end())
  321. {
  322. // Yes, try to retrieve the instancer from the parent type, and add its property values.
  323. decorator_instancer = Factory::GetDecoratorInstancer(it->second.decorator_type);
  324. properties = it->second.properties;
  325. decorator_type = it->second.decorator_type;
  326. }
  327. // If we still don't have an instancer, we cannot continue.
  328. if (!decorator_instancer)
  329. {
  330. Log::Message(Log::LT_WARNING, "Invalid decorator type '%s' declared at %s:%d.", decorator_type.c_str(), stream_file_name.c_str(), line_number);
  331. return false;
  332. }
  333. }
  334. const PropertySpecification& property_specification = decorator_instancer->GetPropertySpecification();
  335. PropertySpecificationParser parser(properties, property_specification);
  336. if (!ReadProperties(parser))
  337. return false;
  338. // Set non-defined properties to their defaults
  339. property_specification.SetPropertyDefaults(properties);
  340. properties.SetSourceOfAllProperties(source);
  341. SharedPtr<Decorator> decorator = decorator_instancer->InstanceDecorator(decorator_type, properties, DecoratorInstancerInterface(style_sheet, source.get()));
  342. if (!decorator)
  343. {
  344. 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);
  345. return false;
  346. }
  347. decorator_map.emplace(name, DecoratorSpecification{ std::move(decorator_type), std::move(properties), std::move(decorator) });
  348. return true;
  349. }
  350. bool StyleSheetParser::ParseMediaFeatureMap(PropertyDictionary& properties, const String & rules)
  351. {
  352. media_query_property_parser->SetTargetProperties(&properties);
  353. enum ParseState { Global, Name, Value };
  354. ParseState state = Name;
  355. char character = 0;
  356. size_t cursor = 0;
  357. String name;
  358. String current_string;
  359. while(cursor++ < rules.length())
  360. {
  361. character = rules[cursor];
  362. switch(character)
  363. {
  364. case '(':
  365. {
  366. if (state != Global)
  367. {
  368. Log::Message(Log::LT_WARNING, "Unexpected '(' in @media query list at %s:%d.", stream_file_name.c_str(), line_number);
  369. return false;
  370. }
  371. current_string = StringUtilities::StripWhitespace(StringUtilities::ToLower(current_string));
  372. if (current_string != "and")
  373. {
  374. 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);
  375. return false;
  376. }
  377. current_string.clear();
  378. state = Name;
  379. }
  380. break;
  381. case ')':
  382. {
  383. if (state != Value)
  384. {
  385. Log::Message(Log::LT_WARNING, "Unexpected ')' in @media query list at %s:%d.", stream_file_name.c_str(), line_number);
  386. return false;
  387. }
  388. current_string = StringUtilities::StripWhitespace(current_string);
  389. if(!media_query_property_parser->Parse(name, current_string))
  390. 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);
  391. current_string.clear();
  392. state = Global;
  393. }
  394. break;
  395. case ':':
  396. {
  397. if (state != Name)
  398. {
  399. Log::Message(Log::LT_WARNING, "Unexpected ':' in @media query list at %s:%d.", stream_file_name.c_str(), line_number);
  400. return false;
  401. }
  402. current_string = StringUtilities::StripWhitespace(StringUtilities::ToLower(current_string));
  403. if (!IsValidIdentifier(current_string))
  404. {
  405. 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);
  406. return false;
  407. }
  408. name = current_string;
  409. current_string.clear();
  410. state = Value;
  411. }
  412. break;
  413. default:
  414. current_string += character;
  415. }
  416. }
  417. if (properties.GetNumProperties() == 0)
  418. {
  419. Log::Message(Log::LT_WARNING, "Media query list parsing yielded no properties at %s:%d.", stream_file_name.c_str(), line_number);
  420. }
  421. return true;
  422. }
  423. bool StyleSheetParser::Parse(MediaBlockList& style_sheets, Stream* _stream, int begin_line_number)
  424. {
  425. RMLUI_ZoneScoped;
  426. int rule_count = 0;
  427. line_number = begin_line_number;
  428. stream = _stream;
  429. stream_file_name = StringUtilities::Replace(stream->GetSourceURL().GetURL(), '|', ':');
  430. enum class State { Global, AtRuleIdentifier, KeyframeBlock, Invalid };
  431. State state = State::Global;
  432. MediaBlock current_block = {};
  433. // Need to track whether currently inside a nested media block or not, since the default scope is also a media block
  434. bool inside_media_block = false;
  435. // At-rules given by the following syntax in global space: @identifier name { block }
  436. String at_rule_name;
  437. // Look for more styles while data is available
  438. while (FillBuffer())
  439. {
  440. String pre_token_str;
  441. while (char token = FindToken(pre_token_str, "{@}", true))
  442. {
  443. switch (state)
  444. {
  445. case State::Global:
  446. {
  447. if (token == '{')
  448. {
  449. // Initialize current block if not present
  450. if (!current_block.stylesheet)
  451. {
  452. current_block = MediaBlock{PropertyDictionary{}, UniquePtr<StyleSheet>(new StyleSheet())};
  453. }
  454. const int rule_line_number = line_number;
  455. // Read the attributes
  456. PropertyDictionary properties;
  457. PropertySpecificationParser parser(properties, StyleSheetSpecification::GetPropertySpecification());
  458. if (!ReadProperties(parser))
  459. continue;
  460. StringList rule_name_list;
  461. StringUtilities::ExpandString(rule_name_list, pre_token_str, ',', '(', ')');
  462. // Add style nodes to the root of the tree
  463. for (size_t i = 0; i < rule_name_list.size(); i++)
  464. {
  465. auto source = MakeShared<PropertySource>(stream_file_name, rule_line_number, rule_name_list[i]);
  466. properties.SetSourceOfAllProperties(source);
  467. if (!ImportProperties(current_block.stylesheet->root.get(), rule_name_list[i], properties, rule_count))
  468. {
  469. Log::Message(Log::LT_WARNING, "Invalid selector '%s' encountered while parsing stylesheet at %s:%d.",
  470. rule_name_list[i].c_str(), stream_file_name.c_str(), line_number);
  471. }
  472. }
  473. rule_count++;
  474. }
  475. else if (token == '@')
  476. {
  477. state = State::AtRuleIdentifier;
  478. }
  479. else if (inside_media_block && token == '}')
  480. {
  481. // Complete current block
  482. PostprocessKeyframes(current_block.stylesheet->keyframes);
  483. current_block.stylesheet->specificity_offset = rule_count;
  484. style_sheets.push_back(std::move(current_block));
  485. current_block = {};
  486. inside_media_block = false;
  487. break;
  488. }
  489. else
  490. {
  491. 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);
  492. }
  493. }
  494. break;
  495. case State::AtRuleIdentifier:
  496. {
  497. if (token == '{')
  498. {
  499. // Initialize current block if not present
  500. if (!current_block.stylesheet)
  501. {
  502. current_block = {PropertyDictionary{}, UniquePtr<StyleSheet>(new StyleSheet())};
  503. }
  504. const String at_rule_identifier = StringUtilities::StripWhitespace(pre_token_str.substr(0, pre_token_str.find(' ')));
  505. at_rule_name = StringUtilities::StripWhitespace(pre_token_str.substr(at_rule_identifier.size()));
  506. if (at_rule_identifier == "keyframes")
  507. {
  508. state = State::KeyframeBlock;
  509. }
  510. else if (at_rule_identifier == "decorator")
  511. {
  512. auto source = MakeShared<PropertySource>(stream_file_name, (int)line_number, pre_token_str);
  513. ParseDecoratorBlock(at_rule_name, current_block.stylesheet->decorator_map, *current_block.stylesheet, source);
  514. at_rule_name.clear();
  515. state = State::Global;
  516. }
  517. else if (at_rule_identifier == "spritesheet")
  518. {
  519. // The spritesheet parser is reasonably heavy to initialize, so we make it a static global.
  520. ReadProperties(*spritesheet_property_parser);
  521. const String& image_source = spritesheet_property_parser->GetImageSource();
  522. const SpriteDefinitionList& sprite_definitions = spritesheet_property_parser->GetSpriteDefinitions();
  523. const float image_resolution_factor = spritesheet_property_parser->GetImageResolutionFactor();
  524. if (sprite_definitions.empty())
  525. {
  526. Log::Message(Log::LT_WARNING, "Spritesheet '%s' has no sprites defined, ignored. At %s:%d", at_rule_name.c_str(), stream_file_name.c_str(), line_number);
  527. }
  528. else if (image_source.empty())
  529. {
  530. 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);
  531. }
  532. else if (image_resolution_factor <= 0.0f || image_resolution_factor >= 100.f)
  533. {
  534. 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);
  535. }
  536. else
  537. {
  538. const float display_scale = 1.0f / image_resolution_factor;
  539. current_block.stylesheet->spritesheet_list.AddSpriteSheet(at_rule_name, image_source, stream_file_name, (int)line_number, display_scale, sprite_definitions);
  540. }
  541. spritesheet_property_parser->Clear();
  542. at_rule_name.clear();
  543. state = State::Global;
  544. }
  545. else if (at_rule_identifier == "media")
  546. {
  547. // complete the current "global" block if present and start a new block
  548. if (current_block.stylesheet)
  549. {
  550. PostprocessKeyframes(current_block.stylesheet->keyframes);
  551. current_block.stylesheet->specificity_offset = rule_count;
  552. style_sheets.push_back(std::move(current_block));
  553. current_block = {};
  554. }
  555. // parse media query list into block
  556. PropertyDictionary feature_map;
  557. ParseMediaFeatureMap(feature_map, at_rule_name);
  558. current_block = {std::move(feature_map), UniquePtr<StyleSheet>(new StyleSheet())};
  559. inside_media_block = true;
  560. state = State::Global;
  561. }
  562. else
  563. {
  564. // Invalid identifier, should ignore
  565. at_rule_name.clear();
  566. state = State::Global;
  567. 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);
  568. }
  569. }
  570. else
  571. {
  572. 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);
  573. state = State::Invalid;
  574. }
  575. }
  576. break;
  577. case State::KeyframeBlock:
  578. {
  579. if (token == '{')
  580. {
  581. // Initialize current block if not present
  582. if (!current_block.stylesheet)
  583. {
  584. current_block = {PropertyDictionary{}, UniquePtr<StyleSheet>(new StyleSheet())};
  585. }
  586. // Each keyframe in keyframes has its own block which is processed here
  587. PropertyDictionary properties;
  588. PropertySpecificationParser parser(properties, StyleSheetSpecification::GetPropertySpecification());
  589. if(!ReadProperties(parser))
  590. continue;
  591. if (!ParseKeyframeBlock(current_block.stylesheet->keyframes, at_rule_name, pre_token_str, properties))
  592. continue;
  593. }
  594. else if (token == '}')
  595. {
  596. at_rule_name.clear();
  597. state = State::Global;
  598. }
  599. else
  600. {
  601. 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);
  602. state = State::Invalid;
  603. }
  604. }
  605. break;
  606. default:
  607. RMLUI_ERROR;
  608. state = State::Invalid;
  609. break;
  610. }
  611. if (state == State::Invalid)
  612. break;
  613. }
  614. if (state == State::Invalid)
  615. break;
  616. }
  617. // Complete last block if present
  618. if (current_block.stylesheet)
  619. {
  620. PostprocessKeyframes(current_block.stylesheet->keyframes);
  621. current_block.stylesheet->specificity_offset = rule_count;
  622. style_sheets.push_back(std::move(current_block));
  623. }
  624. return !style_sheets.empty();
  625. }
  626. bool StyleSheetParser::ParseProperties(PropertyDictionary& parsed_properties, const String& properties)
  627. {
  628. RMLUI_ASSERT(!stream);
  629. StreamMemory stream_owner((const byte*)properties.c_str(), properties.size());
  630. stream = &stream_owner;
  631. PropertySpecificationParser parser(parsed_properties, StyleSheetSpecification::GetPropertySpecification());
  632. bool success = ReadProperties(parser);
  633. stream = nullptr;
  634. return success;
  635. }
  636. StyleSheetNodeListRaw StyleSheetParser::ConstructNodes(StyleSheetNode& root_node, const String& selectors)
  637. {
  638. const PropertyDictionary empty_properties;
  639. StringList selector_list;
  640. StringUtilities::ExpandString(selector_list, selectors, ',', '(', ')');
  641. StyleSheetNodeListRaw leaf_nodes;
  642. for (const String& selector : selector_list)
  643. {
  644. StyleSheetNode* leaf_node = ImportProperties(&root_node, selector, empty_properties, 0);
  645. if (!leaf_node)
  646. Log::Message(Log::LT_WARNING, "Invalid selector '%s' encountered.", selector.c_str());
  647. else if (leaf_node != &root_node)
  648. leaf_nodes.push_back(leaf_node);
  649. }
  650. return leaf_nodes;
  651. }
  652. bool StyleSheetParser::ReadProperties(AbstractPropertyParser& property_parser)
  653. {
  654. RMLUI_ZoneScoped;
  655. String name;
  656. String value;
  657. enum ParseState { NAME, VALUE, QUOTE };
  658. ParseState state = NAME;
  659. char character;
  660. char previous_character = 0;
  661. while (ReadCharacter(character))
  662. {
  663. parse_buffer_pos++;
  664. switch (state)
  665. {
  666. case NAME:
  667. {
  668. if (character == ';')
  669. {
  670. name = StringUtilities::StripWhitespace(name);
  671. if (!name.empty())
  672. {
  673. 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);
  674. name.clear();
  675. }
  676. }
  677. else if (character == '}')
  678. {
  679. name = StringUtilities::StripWhitespace(name);
  680. if (!name.empty())
  681. 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);
  682. return true;
  683. }
  684. else if (character == ':')
  685. {
  686. name = StringUtilities::StripWhitespace(name);
  687. state = VALUE;
  688. }
  689. else
  690. name += character;
  691. }
  692. break;
  693. case VALUE:
  694. {
  695. if (character == ';')
  696. {
  697. value = StringUtilities::StripWhitespace(value);
  698. if (!property_parser.Parse(name, value))
  699. 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);
  700. name.clear();
  701. value.clear();
  702. state = NAME;
  703. }
  704. else if (character == '}')
  705. {
  706. break;
  707. }
  708. else
  709. {
  710. value += character;
  711. if (character == '"')
  712. state = QUOTE;
  713. }
  714. }
  715. break;
  716. case QUOTE:
  717. {
  718. value += character;
  719. if (character == '"' && previous_character != '\\')
  720. state = VALUE;
  721. }
  722. break;
  723. }
  724. if (character == '}')
  725. break;
  726. previous_character = character;
  727. }
  728. if (state == VALUE && !name.empty() && !value.empty())
  729. {
  730. value = StringUtilities::StripWhitespace(value);
  731. if (!property_parser.Parse(name, value))
  732. 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);
  733. }
  734. else if (!StringUtilities::StripWhitespace(name).empty() || !value.empty())
  735. {
  736. 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);
  737. }
  738. return true;
  739. }
  740. StyleSheetNode* StyleSheetParser::ImportProperties(StyleSheetNode* node, const String& rule, const PropertyDictionary& properties,
  741. int rule_specificity)
  742. {
  743. StyleSheetNode* leaf_node = node;
  744. // Create each node going down the tree.
  745. for (size_t index = 0; index < rule.size();)
  746. {
  747. CompoundSelector selector;
  748. // Determine the combinator connecting the previous node if any.
  749. for (; index > 0 && index < rule.size(); index++)
  750. {
  751. bool reached_end_of_combinators = false;
  752. switch (rule[index])
  753. {
  754. case ' ': break;
  755. case '>': selector.combinator = SelectorCombinator::Child; break;
  756. case '+': selector.combinator = SelectorCombinator::NextSibling; break;
  757. case '~': selector.combinator = SelectorCombinator::SubsequentSibling; break;
  758. default: reached_end_of_combinators = true; break;
  759. }
  760. if (reached_end_of_combinators)
  761. break;
  762. }
  763. // Determine the node's requirements.
  764. while (index < rule.size())
  765. {
  766. size_t start_index = index;
  767. size_t end_index = index + 1;
  768. if (rule[start_index] == '*')
  769. start_index += 1;
  770. if (rule[start_index] == '[')
  771. {
  772. end_index = rule.find(']', start_index + 1);
  773. if (end_index == String::npos)
  774. return nullptr;
  775. end_index += 1;
  776. }
  777. else
  778. {
  779. int parenthesis_count = 0;
  780. // Read until we hit the next identifier. Don't match inside parenthesis in case of structural selectors.
  781. for (; end_index < rule.size(); end_index++)
  782. {
  783. static const String identifiers = "#.:[ >+~";
  784. if (parenthesis_count == 0 && identifiers.find(rule[end_index]) != String::npos)
  785. break;
  786. if (rule[end_index] == '(')
  787. parenthesis_count += 1;
  788. else if (rule[end_index] == ')')
  789. parenthesis_count -= 1;
  790. }
  791. }
  792. if (end_index > start_index)
  793. {
  794. const char* p_begin = rule.data() + start_index;
  795. const char* p_end = rule.data() + end_index;
  796. switch (rule[start_index])
  797. {
  798. case '#': selector.id = String(p_begin + 1, p_end); break;
  799. case '.': selector.class_names.push_back(String(p_begin + 1, p_end)); break;
  800. case ':':
  801. {
  802. String pseudo_class_name = String(p_begin + 1, p_end);
  803. StructuralSelector node_selector = StyleSheetFactory::GetSelector(pseudo_class_name);
  804. if (node_selector.type != StructuralSelectorType::Invalid)
  805. selector.structural_selectors.push_back(node_selector);
  806. else
  807. selector.pseudo_class_names.push_back(std::move(pseudo_class_name));
  808. }
  809. break;
  810. case '[':
  811. {
  812. const size_t i_attr_begin = start_index + 1;
  813. const size_t i_attr_end = end_index - 1;
  814. if (i_attr_end <= i_attr_begin)
  815. return nullptr;
  816. AttributeSelector attribute;
  817. static const String attribute_operators = "=~|^$*]";
  818. size_t i_cursor = Math::Min(rule.find_first_of(attribute_operators, i_attr_begin), i_attr_end);
  819. attribute.name = rule.substr(i_attr_begin, i_cursor - i_attr_begin);
  820. if (i_cursor < i_attr_end)
  821. {
  822. const char c = rule[i_cursor];
  823. attribute.type = AttributeSelectorType(c);
  824. // Move cursor past operator. Non-'=' symbols are always followed by '=' so move two characters.
  825. i_cursor += (c == '=' ? 1 : 2);
  826. size_t i_value_end = i_attr_end;
  827. if (i_cursor < i_attr_end && (rule[i_cursor] == '"' || rule[i_cursor] == '\''))
  828. {
  829. i_cursor += 1;
  830. i_value_end -= 1;
  831. }
  832. if (i_cursor < i_value_end)
  833. attribute.value = rule.substr(i_cursor, i_value_end - i_cursor);
  834. }
  835. selector.attributes.push_back(std::move(attribute));
  836. }
  837. break;
  838. default: selector.tag = String(p_begin, p_end); break;
  839. }
  840. }
  841. index = end_index;
  842. // If we reached a combinator then we submit the current node and start fresh with a new node.
  843. static const String combinators(" >+~");
  844. if (combinators.find(rule[index]) != String::npos)
  845. break;
  846. }
  847. // Sort the classes and pseudo-classes so they are consistent across equivalent declarations that shuffle the order around.
  848. std::sort(selector.class_names.begin(), selector.class_names.end());
  849. std::sort(selector.attributes.begin(), selector.attributes.end());
  850. std::sort(selector.pseudo_class_names.begin(), selector.pseudo_class_names.end());
  851. std::sort(selector.structural_selectors.begin(), selector.structural_selectors.end());
  852. // Add the new child node, or retrieve the existing child if we have an exact match.
  853. leaf_node = leaf_node->GetOrCreateChildNode(std::move(selector));
  854. }
  855. // Merge the new properties with those already on the leaf node.
  856. leaf_node->ImportProperties(properties, rule_specificity);
  857. return leaf_node;
  858. }
  859. char StyleSheetParser::FindToken(String& buffer, const char* tokens, bool remove_token)
  860. {
  861. buffer.clear();
  862. char character;
  863. while (ReadCharacter(character))
  864. {
  865. if (strchr(tokens, character) != nullptr)
  866. {
  867. if (remove_token)
  868. parse_buffer_pos++;
  869. return character;
  870. }
  871. else
  872. {
  873. buffer += character;
  874. parse_buffer_pos++;
  875. }
  876. }
  877. return 0;
  878. }
  879. // Attempts to find the next character in the active stream.
  880. bool StyleSheetParser::ReadCharacter(char& buffer)
  881. {
  882. bool comment = false;
  883. // Continuously fill the buffer until either we run out of
  884. // stream or we find the requested token
  885. do
  886. {
  887. while (parse_buffer_pos < parse_buffer.size())
  888. {
  889. if (parse_buffer[parse_buffer_pos] == '\n')
  890. line_number++;
  891. else if (comment)
  892. {
  893. // Check for closing comment
  894. if (parse_buffer[parse_buffer_pos] == '*')
  895. {
  896. parse_buffer_pos++;
  897. if (parse_buffer_pos >= parse_buffer.size())
  898. {
  899. if (!FillBuffer())
  900. return false;
  901. }
  902. if (parse_buffer[parse_buffer_pos] == '/')
  903. comment = false;
  904. }
  905. }
  906. else
  907. {
  908. // Check for an opening comment
  909. if (parse_buffer[parse_buffer_pos] == '/')
  910. {
  911. parse_buffer_pos++;
  912. if (parse_buffer_pos >= parse_buffer.size())
  913. {
  914. if (!FillBuffer())
  915. {
  916. buffer = '/';
  917. parse_buffer = "/";
  918. return true;
  919. }
  920. }
  921. if (parse_buffer[parse_buffer_pos] == '*')
  922. comment = true;
  923. else
  924. {
  925. buffer = '/';
  926. if (parse_buffer_pos == 0)
  927. parse_buffer.insert(parse_buffer_pos, 1, '/');
  928. else
  929. parse_buffer_pos--;
  930. return true;
  931. }
  932. }
  933. if (!comment)
  934. {
  935. // If we find a character, return it
  936. buffer = parse_buffer[parse_buffer_pos];
  937. return true;
  938. }
  939. }
  940. parse_buffer_pos++;
  941. }
  942. }
  943. while (FillBuffer());
  944. return false;
  945. }
  946. // Fills the internal buffer with more content
  947. bool StyleSheetParser::FillBuffer()
  948. {
  949. // If theres no data to process, abort
  950. if (stream->IsEOS())
  951. return false;
  952. // Read in some data (4092 instead of 4096 to avoid the buffer growing when we have to add back
  953. // a character after a failed comment parse.)
  954. parse_buffer.clear();
  955. bool read = stream->Read(parse_buffer, 4092) > 0;
  956. parse_buffer_pos = 0;
  957. return read;
  958. }
  959. } // namespace Rml