StyleSheetParser.cpp 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157
  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-2023 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 "../../Include/RmlUi/Core/Decorator.h"
  30. #include "../../Include/RmlUi/Core/Factory.h"
  31. #include "../../Include/RmlUi/Core/Log.h"
  32. #include "../../Include/RmlUi/Core/Profiling.h"
  33. #include "../../Include/RmlUi/Core/PropertyDefinition.h"
  34. #include "../../Include/RmlUi/Core/PropertySpecification.h"
  35. #include "../../Include/RmlUi/Core/StreamMemory.h"
  36. #include "../../Include/RmlUi/Core/StyleSheet.h"
  37. #include "../../Include/RmlUi/Core/StyleSheetContainer.h"
  38. #include "../../Include/RmlUi/Core/StyleSheetSpecification.h"
  39. #include "ComputeProperty.h"
  40. #include "ControlledLifetimeResource.h"
  41. #include "StyleSheetFactory.h"
  42. #include "StyleSheetNode.h"
  43. #include <algorithm>
  44. #include <string.h>
  45. namespace Rml {
  46. class AbstractPropertyParser : NonCopyMoveable {
  47. protected:
  48. ~AbstractPropertyParser() = default;
  49. public:
  50. virtual bool Parse(const String& name, const String& value) = 0;
  51. };
  52. /*
  53. * PropertySpecificationParser just passes the parsing to a property specification. Usually
  54. * the main stylesheet specification, except for e.g. @decorator blocks.
  55. */
  56. class PropertySpecificationParser final : public AbstractPropertyParser {
  57. private:
  58. // The dictionary to store the properties in.
  59. PropertyDictionary& properties;
  60. // The specification used to parse the values. Normally the default stylesheet specification, but not for e.g. all at-rules such as decorators.
  61. const PropertySpecification& specification;
  62. public:
  63. PropertySpecificationParser(PropertyDictionary& properties, const PropertySpecification& specification) :
  64. properties(properties), specification(specification)
  65. {}
  66. bool Parse(const String& name, const String& value) override { return specification.ParsePropertyDeclaration(properties, name, value); }
  67. };
  68. /*
  69. * Spritesheets need a special parser because its property names are arbitrary keys,
  70. * while its values are always rectangles. Thus, it must be parsed with a special "rectangle" parser
  71. * for every name-value pair. We can probably optimize this for @performance.
  72. */
  73. class SpritesheetPropertyParser final : public AbstractPropertyParser {
  74. private:
  75. String image_source;
  76. float image_resolution_factor = 1.f;
  77. SpriteDefinitionList sprite_definitions;
  78. PropertyDictionary properties;
  79. PropertySpecification specification;
  80. PropertyId id_src, id_rx, id_ry, id_rw, id_rh, id_resolution;
  81. ShorthandId id_rectangle;
  82. public:
  83. SpritesheetPropertyParser() : specification(6, 1)
  84. {
  85. id_src = specification.RegisterProperty("src", "", false, false).AddParser("string").GetId();
  86. id_rx = specification.RegisterProperty("rectangle-x", "", false, false).AddParser("length").GetId();
  87. id_ry = specification.RegisterProperty("rectangle-y", "", false, false).AddParser("length").GetId();
  88. id_rw = specification.RegisterProperty("rectangle-w", "", false, false).AddParser("length").GetId();
  89. id_rh = specification.RegisterProperty("rectangle-h", "", false, false).AddParser("length").GetId();
  90. id_rectangle = specification.RegisterShorthand("rectangle", "rectangle-x, rectangle-y, rectangle-w, rectangle-h", ShorthandType::FallThrough);
  91. id_resolution = specification.RegisterProperty("resolution", "", false, false).AddParser("resolution").GetId();
  92. }
  93. const String& GetImageSource() const { return image_source; }
  94. const SpriteDefinitionList& GetSpriteDefinitions() const { return sprite_definitions; }
  95. float GetImageResolutionFactor() const { return image_resolution_factor; }
  96. void Clear()
  97. {
  98. image_resolution_factor = 1.f;
  99. image_source.clear();
  100. sprite_definitions.clear();
  101. }
  102. bool Parse(const String& name, const String& value) override
  103. {
  104. if (name == "src")
  105. {
  106. if (!specification.ParsePropertyDeclaration(properties, id_src, value))
  107. return false;
  108. if (const Property* property = properties.GetProperty(id_src))
  109. {
  110. if (property->unit == Unit::STRING)
  111. image_source = property->Get<String>();
  112. }
  113. }
  114. else if (name == "resolution")
  115. {
  116. if (!specification.ParsePropertyDeclaration(properties, id_resolution, value))
  117. return false;
  118. if (const Property* property = properties.GetProperty(id_resolution))
  119. {
  120. if (property->unit == Unit::X)
  121. image_resolution_factor = property->Get<float>();
  122. }
  123. }
  124. else
  125. {
  126. if (!specification.ParseShorthandDeclaration(properties, id_rectangle, value))
  127. return false;
  128. Vector2f position, size;
  129. if (auto p = properties.GetProperty(id_rx))
  130. position.x = p->Get<float>();
  131. if (auto p = properties.GetProperty(id_ry))
  132. position.y = p->Get<float>();
  133. if (auto p = properties.GetProperty(id_rw))
  134. size.x = p->Get<float>();
  135. if (auto p = properties.GetProperty(id_rh))
  136. size.y = p->Get<float>();
  137. sprite_definitions.emplace_back(name, Rectanglef::FromPositionSize(position, size));
  138. }
  139. return true;
  140. }
  141. };
  142. /*
  143. * Media queries need a special parser because they have unique properties that
  144. * aren't admissible in other property declaration contexts.
  145. */
  146. class MediaQueryPropertyParser final : public AbstractPropertyParser {
  147. private:
  148. // The dictionary to store the properties in.
  149. PropertyDictionary* properties = nullptr;
  150. PropertySpecification specification;
  151. static PropertyId CastId(MediaQueryId id) { return static_cast<PropertyId>(id); }
  152. public:
  153. MediaQueryPropertyParser() : specification(14, 0)
  154. {
  155. specification.RegisterProperty("width", "", false, false, CastId(MediaQueryId::Width)).AddParser("length");
  156. specification.RegisterProperty("min-width", "", false, false, CastId(MediaQueryId::MinWidth)).AddParser("length");
  157. specification.RegisterProperty("max-width", "", false, false, CastId(MediaQueryId::MaxWidth)).AddParser("length");
  158. specification.RegisterProperty("height", "", false, false, CastId(MediaQueryId::Height)).AddParser("length");
  159. specification.RegisterProperty("min-height", "", false, false, CastId(MediaQueryId::MinHeight)).AddParser("length");
  160. specification.RegisterProperty("max-height", "", false, false, CastId(MediaQueryId::MaxHeight)).AddParser("length");
  161. specification.RegisterProperty("aspect-ratio", "", false, false, CastId(MediaQueryId::AspectRatio)).AddParser("ratio");
  162. specification.RegisterProperty("min-aspect-ratio", "", false, false, CastId(MediaQueryId::MinAspectRatio)).AddParser("ratio");
  163. specification.RegisterProperty("max-aspect-ratio", "", false, false, CastId(MediaQueryId::MaxAspectRatio)).AddParser("ratio");
  164. specification.RegisterProperty("resolution", "", false, false, CastId(MediaQueryId::Resolution)).AddParser("resolution");
  165. specification.RegisterProperty("min-resolution", "", false, false, CastId(MediaQueryId::MinResolution)).AddParser("resolution");
  166. specification.RegisterProperty("max-resolution", "", false, false, CastId(MediaQueryId::MaxResolution)).AddParser("resolution");
  167. specification.RegisterProperty("orientation", "", false, false, CastId(MediaQueryId::Orientation))
  168. .AddParser("keyword", "landscape, portrait");
  169. specification.RegisterProperty("theme", "", false, false, CastId(MediaQueryId::Theme)).AddParser("string");
  170. }
  171. void SetTargetProperties(PropertyDictionary* _properties) { properties = _properties; }
  172. void Clear() { properties = nullptr; }
  173. bool Parse(const String& name, const String& value) override
  174. {
  175. RMLUI_ASSERT(properties);
  176. return specification.ParsePropertyDeclaration(*properties, name, value);
  177. }
  178. };
  179. struct StyleSheetParserData {
  180. // The following parsers are reasonably heavy to initialize, so we construct them during library initialization.
  181. SpritesheetPropertyParser spritesheet;
  182. MediaQueryPropertyParser media_query;
  183. };
  184. static ControlledLifetimeResource<StyleSheetParserData> style_sheet_property_parsers;
  185. StyleSheetParser::StyleSheetParser()
  186. {
  187. line_number = 0;
  188. stream = nullptr;
  189. parse_buffer_pos = 0;
  190. }
  191. StyleSheetParser::~StyleSheetParser() {}
  192. void StyleSheetParser::Initialise()
  193. {
  194. style_sheet_property_parsers.Initialize();
  195. }
  196. void StyleSheetParser::Shutdown()
  197. {
  198. style_sheet_property_parsers.Shutdown();
  199. }
  200. static bool IsValidIdentifier(const String& str)
  201. {
  202. if (str.empty())
  203. return false;
  204. for (size_t i = 0; i < str.size(); i++)
  205. {
  206. char c = str[i];
  207. bool valid = ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c == '-') || (c == '_'));
  208. if (!valid)
  209. return false;
  210. }
  211. return true;
  212. }
  213. static void PostprocessKeyframes(KeyframesMap& keyframes_map)
  214. {
  215. for (auto& keyframes_pair : keyframes_map)
  216. {
  217. Keyframes& keyframes = keyframes_pair.second;
  218. auto& blocks = keyframes.blocks;
  219. auto& property_ids = keyframes.property_ids;
  220. // Sort keyframes on selector value.
  221. std::sort(blocks.begin(), blocks.end(), [](const KeyframeBlock& a, const KeyframeBlock& b) { return a.normalized_time < b.normalized_time; });
  222. // Add all property names specified by any block
  223. if (blocks.size() > 0)
  224. property_ids.reserve(blocks.size() * blocks[0].properties.GetNumProperties());
  225. for (auto& block : blocks)
  226. {
  227. for (auto& property : block.properties.GetProperties())
  228. property_ids.push_back(property.first);
  229. }
  230. // Remove duplicate property names
  231. std::sort(property_ids.begin(), property_ids.end());
  232. property_ids.erase(std::unique(property_ids.begin(), property_ids.end()), property_ids.end());
  233. property_ids.shrink_to_fit();
  234. }
  235. }
  236. bool StyleSheetParser::ParseKeyframeBlock(KeyframesMap& keyframes_map, const String& identifier, const String& rules,
  237. const PropertyDictionary& properties)
  238. {
  239. if (!IsValidIdentifier(identifier))
  240. {
  241. Log::Message(Log::LT_WARNING, "Invalid keyframes identifier '%s' at %s:%d", identifier.c_str(), stream_file_name.c_str(), line_number);
  242. return false;
  243. }
  244. if (properties.GetNumProperties() == 0)
  245. return true;
  246. StringList rule_list;
  247. StringUtilities::ExpandString(rule_list, rules);
  248. Vector<float> rule_values;
  249. rule_values.reserve(rule_list.size());
  250. for (auto rule : rule_list)
  251. {
  252. float value = 0.0f;
  253. int count = 0;
  254. rule = StringUtilities::ToLower(std::move(rule));
  255. if (rule == "from")
  256. rule_values.push_back(0.0f);
  257. else if (rule == "to")
  258. rule_values.push_back(1.0f);
  259. else if (sscanf(rule.c_str(), "%f%%%n", &value, &count) == 1)
  260. if (count > 0 && value >= 0.0f && value <= 100.0f)
  261. rule_values.push_back(0.01f * value);
  262. }
  263. if (rule_values.empty())
  264. {
  265. Log::Message(Log::LT_WARNING, "Invalid keyframes rule(s) '%s' at %s:%d", rules.c_str(), stream_file_name.c_str(), line_number);
  266. return false;
  267. }
  268. Keyframes& keyframes = keyframes_map[identifier];
  269. for (float selector : rule_values)
  270. {
  271. auto it = std::find_if(keyframes.blocks.begin(), keyframes.blocks.end(),
  272. [selector](const KeyframeBlock& keyframe_block) { return Math::Absolute(keyframe_block.normalized_time - selector) < 0.0001f; });
  273. if (it == keyframes.blocks.end())
  274. {
  275. keyframes.blocks.emplace_back(selector);
  276. it = (keyframes.blocks.end() - 1);
  277. }
  278. else
  279. {
  280. // In case of duplicate keyframes, we only use the latest definition as per CSS rules
  281. it->properties = PropertyDictionary();
  282. }
  283. it->properties.Import(properties);
  284. }
  285. return true;
  286. }
  287. bool StyleSheetParser::ParseDecoratorBlock(const String& at_name, NamedDecoratorMap& named_decorator_map,
  288. const SharedPtr<const PropertySource>& source)
  289. {
  290. StringList name_type;
  291. StringUtilities::ExpandString(name_type, at_name, ':');
  292. if (name_type.size() != 2 || name_type[0].empty() || name_type[1].empty())
  293. {
  294. Log::Message(Log::LT_WARNING, "Decorator syntax error at %s:%d. Use syntax: '@decorator name : type { ... }'.", stream_file_name.c_str(),
  295. line_number);
  296. return false;
  297. }
  298. const String& name = name_type[0];
  299. String decorator_type = name_type[1];
  300. auto it_find = named_decorator_map.find(name);
  301. if (it_find != named_decorator_map.end())
  302. {
  303. Log::Message(Log::LT_WARNING, "Decorator with name '%s' already declared, ignoring decorator at %s:%d.", name.c_str(),
  304. stream_file_name.c_str(), line_number);
  305. return false;
  306. }
  307. // Get the instancer associated with the decorator type
  308. DecoratorInstancer* decorator_instancer = Factory::GetDecoratorInstancer(decorator_type);
  309. PropertyDictionary properties;
  310. if (!decorator_instancer)
  311. {
  312. // Type is not a declared decorator type, instead, see if it is another decorator name, then we inherit its properties.
  313. auto it = named_decorator_map.find(decorator_type);
  314. if (it != named_decorator_map.end())
  315. {
  316. // Yes, try to retrieve the instancer from the parent type, and add its property values.
  317. decorator_instancer = Factory::GetDecoratorInstancer(it->second.type);
  318. properties = it->second.properties;
  319. decorator_type = it->second.type;
  320. }
  321. // If we still don't have an instancer, we cannot continue.
  322. if (!decorator_instancer)
  323. {
  324. Log::Message(Log::LT_WARNING, "Invalid decorator type '%s' declared at %s:%d.", decorator_type.c_str(), stream_file_name.c_str(),
  325. line_number);
  326. return false;
  327. }
  328. }
  329. const PropertySpecification& property_specification = decorator_instancer->GetPropertySpecification();
  330. PropertySpecificationParser parser(properties, property_specification);
  331. ReadProperties(parser);
  332. // Set non-defined properties to their defaults
  333. property_specification.SetPropertyDefaults(properties);
  334. properties.SetSourceOfAllProperties(source);
  335. named_decorator_map.emplace(name, NamedDecorator{std::move(decorator_type), decorator_instancer, std::move(properties)});
  336. return true;
  337. }
  338. bool StyleSheetParser::ParseMediaFeatureMap(const String& rules, PropertyDictionary& properties, MediaQueryModifier& modifier)
  339. {
  340. style_sheet_property_parsers->media_query.SetTargetProperties(&properties);
  341. enum ParseState { Global, Name, Value };
  342. ParseState state = Global;
  343. char character = 0;
  344. String name;
  345. String current_string;
  346. modifier = MediaQueryModifier::None;
  347. for (size_t cursor = 0; cursor < rules.length(); cursor++)
  348. {
  349. character = rules[cursor];
  350. switch (character)
  351. {
  352. case ' ':
  353. {
  354. if (state == Global)
  355. {
  356. current_string = StringUtilities::StripWhitespace(StringUtilities::ToLower(std::move(current_string)));
  357. if (current_string == "not")
  358. {
  359. // we can only ever see one "not" on the entire global query.
  360. if (modifier != MediaQueryModifier::None)
  361. {
  362. Log::Message(Log::LT_WARNING, "Unexpected '%s' in @media query list at %s:%d.", current_string.c_str(),
  363. stream_file_name.c_str(), line_number);
  364. return false;
  365. }
  366. modifier = MediaQueryModifier::Not;
  367. current_string.clear();
  368. }
  369. }
  370. break;
  371. }
  372. case '(':
  373. {
  374. if (state != Global)
  375. {
  376. Log::Message(Log::LT_WARNING, "Unexpected '(' in @media query list at %s:%d.", stream_file_name.c_str(), line_number);
  377. return false;
  378. }
  379. current_string = StringUtilities::StripWhitespace(StringUtilities::ToLower(std::move(current_string)));
  380. // allow an empty string to pass through only if we had just parsed a modifier.
  381. if (current_string != "and" && (properties.GetNumProperties() != 0 || !current_string.empty()))
  382. {
  383. Log::Message(Log::LT_WARNING, "Unexpected '%s' in @media query list at %s:%d. Expected 'and'.", current_string.c_str(),
  384. stream_file_name.c_str(), line_number);
  385. return false;
  386. }
  387. current_string.clear();
  388. state = Name;
  389. }
  390. break;
  391. case ')':
  392. {
  393. if (state != Value)
  394. {
  395. Log::Message(Log::LT_WARNING, "Unexpected ')' in @media query list at %s:%d.", stream_file_name.c_str(), line_number);
  396. return false;
  397. }
  398. current_string = StringUtilities::StripWhitespace(current_string);
  399. if (!style_sheet_property_parsers->media_query.Parse(name, current_string))
  400. Log::Message(Log::LT_WARNING, "Syntax error parsing media-query property declaration '%s: %s;' in %s: %d.", name.c_str(),
  401. current_string.c_str(), stream_file_name.c_str(), line_number);
  402. current_string.clear();
  403. state = Global;
  404. }
  405. break;
  406. case ':':
  407. {
  408. if (state != Name)
  409. {
  410. Log::Message(Log::LT_WARNING, "Unexpected ':' in @media query list at %s:%d.", stream_file_name.c_str(), line_number);
  411. return false;
  412. }
  413. current_string = StringUtilities::StripWhitespace(StringUtilities::ToLower(std::move(current_string)));
  414. if (!IsValidIdentifier(current_string))
  415. {
  416. Log::Message(Log::LT_WARNING, "Malformed property name '%s' in @media query list at %s:%d.", current_string.c_str(),
  417. stream_file_name.c_str(), line_number);
  418. return false;
  419. }
  420. name = current_string;
  421. current_string.clear();
  422. state = Value;
  423. }
  424. break;
  425. default: current_string += character;
  426. }
  427. }
  428. if (properties.GetNumProperties() == 0)
  429. {
  430. Log::Message(Log::LT_WARNING, "Media query list parsing yielded no properties at %s:%d.", stream_file_name.c_str(), line_number);
  431. }
  432. return true;
  433. }
  434. bool StyleSheetParser::Parse(MediaBlockList& style_sheets, Stream* _stream, int begin_line_number)
  435. {
  436. RMLUI_ZoneScoped;
  437. int rule_count = 0;
  438. line_number = begin_line_number;
  439. stream = _stream;
  440. parse_buffer.clear();
  441. parse_buffer_pos = 0;
  442. stream_file_name = StringUtilities::Replace(stream->GetSourceURL().GetURL(), '|', ':');
  443. enum class State { Global, AtRuleIdentifier, KeyframeBlock, Invalid };
  444. State state = State::Global;
  445. MediaBlock current_block = {};
  446. // Need to track whether currently inside a nested media block or not, since the default scope is also a media block
  447. bool inside_media_block = false;
  448. // At-rules given by the following syntax in global space: @identifier name { block }
  449. String at_rule_name;
  450. // Look for more styles while data is available
  451. while (FillBuffer())
  452. {
  453. String pre_token_str;
  454. while (char token = FindAnyToken(pre_token_str, "{@}"))
  455. {
  456. switch (state)
  457. {
  458. case State::Global:
  459. {
  460. if (token == '{')
  461. {
  462. // Initialize current block if not present
  463. if (!current_block.stylesheet)
  464. {
  465. current_block = MediaBlock{PropertyDictionary{}, UniquePtr<StyleSheet>(new StyleSheet()), MediaQueryModifier::None};
  466. }
  467. const int rule_line_number = line_number;
  468. // Read the attributes
  469. PropertyDictionary properties;
  470. PropertySpecificationParser parser(properties, StyleSheetSpecification::GetPropertySpecification());
  471. ReadProperties(parser);
  472. StringList rule_name_list;
  473. StringUtilities::ExpandString(rule_name_list, pre_token_str, ',', '(', ')');
  474. // Add style nodes to the root of the tree
  475. for (size_t i = 0; i < rule_name_list.size(); i++)
  476. {
  477. auto source = MakeShared<PropertySource>(stream_file_name, rule_line_number, rule_name_list[i]);
  478. properties.SetSourceOfAllProperties(source);
  479. if (!ImportProperties(current_block.stylesheet->root.get(), rule_name_list[i], properties, rule_count))
  480. {
  481. Log::Message(Log::LT_WARNING, "Invalid selector '%s' encountered while parsing stylesheet at %s:%d.",
  482. rule_name_list[i].c_str(), stream_file_name.c_str(), line_number);
  483. }
  484. }
  485. rule_count++;
  486. }
  487. else if (token == '@')
  488. {
  489. state = State::AtRuleIdentifier;
  490. }
  491. else if (inside_media_block && token == '}')
  492. {
  493. // Complete current block
  494. PostprocessKeyframes(current_block.stylesheet->keyframes);
  495. current_block.stylesheet->specificity_offset = rule_count;
  496. style_sheets.push_back(std::move(current_block));
  497. current_block = {};
  498. inside_media_block = false;
  499. break;
  500. }
  501. else
  502. {
  503. Log::Message(Log::LT_WARNING, "Invalid character '%c' found while parsing stylesheet at %s:%d. Trying to proceed.", token,
  504. stream_file_name.c_str(), line_number);
  505. }
  506. }
  507. break;
  508. case State::AtRuleIdentifier:
  509. {
  510. if (token == '{')
  511. {
  512. // Initialize current block if not present
  513. if (!current_block.stylesheet)
  514. {
  515. current_block = {PropertyDictionary{}, UniquePtr<StyleSheet>(new StyleSheet()), MediaQueryModifier::None};
  516. }
  517. const String at_rule_identifier = StringUtilities::StripWhitespace(pre_token_str.substr(0, pre_token_str.find(' ')));
  518. at_rule_name = StringUtilities::StripWhitespace(pre_token_str.substr(at_rule_identifier.size()));
  519. if (at_rule_identifier == "keyframes")
  520. {
  521. state = State::KeyframeBlock;
  522. }
  523. else if (at_rule_identifier == "decorator")
  524. {
  525. auto source = MakeShared<PropertySource>(stream_file_name, (int)line_number, pre_token_str);
  526. ParseDecoratorBlock(at_rule_name, current_block.stylesheet->named_decorator_map, source);
  527. at_rule_name.clear();
  528. state = State::Global;
  529. }
  530. else if (at_rule_identifier == "spritesheet")
  531. {
  532. auto& spritesheet_property_parser = style_sheet_property_parsers->spritesheet;
  533. ReadProperties(spritesheet_property_parser);
  534. const String& image_source = spritesheet_property_parser.GetImageSource();
  535. const SpriteDefinitionList& sprite_definitions = spritesheet_property_parser.GetSpriteDefinitions();
  536. const float image_resolution_factor = spritesheet_property_parser.GetImageResolutionFactor();
  537. if (sprite_definitions.empty())
  538. {
  539. Log::Message(Log::LT_WARNING, "Spritesheet '%s' has no sprites defined, ignored. At %s:%d", at_rule_name.c_str(),
  540. stream_file_name.c_str(), line_number);
  541. }
  542. else if (image_source.empty())
  543. {
  544. Log::Message(Log::LT_WARNING, "No image source (property 'src') specified for spritesheet '%s'. At %s:%d",
  545. at_rule_name.c_str(), stream_file_name.c_str(), line_number);
  546. }
  547. else if (image_resolution_factor <= 0.0f || image_resolution_factor >= 100.f)
  548. {
  549. Log::Message(Log::LT_WARNING,
  550. "Spritesheet resolution (property 'resolution') value must be larger than 0.0 and smaller than 100.0, given %g. In "
  551. "spritesheet '%s'. At %s:%d",
  552. image_resolution_factor, at_rule_name.c_str(), stream_file_name.c_str(), line_number);
  553. }
  554. else
  555. {
  556. const float display_scale = 1.0f / image_resolution_factor;
  557. current_block.stylesheet->spritesheet_list.AddSpriteSheet(at_rule_name, image_source, stream_file_name, (int)line_number,
  558. display_scale, sprite_definitions);
  559. }
  560. spritesheet_property_parser.Clear();
  561. at_rule_name.clear();
  562. state = State::Global;
  563. }
  564. else if (at_rule_identifier == "media")
  565. {
  566. // complete the current "global" block if present and start a new block
  567. if (current_block.stylesheet)
  568. {
  569. PostprocessKeyframes(current_block.stylesheet->keyframes);
  570. current_block.stylesheet->specificity_offset = rule_count;
  571. style_sheets.push_back(std::move(current_block));
  572. current_block = {};
  573. }
  574. // parse media query list into block
  575. PropertyDictionary feature_map;
  576. MediaQueryModifier modifier;
  577. ParseMediaFeatureMap(at_rule_name, feature_map, modifier);
  578. current_block = {std::move(feature_map), UniquePtr<StyleSheet>(new StyleSheet()), modifier};
  579. inside_media_block = true;
  580. state = State::Global;
  581. }
  582. else
  583. {
  584. // Invalid identifier, should ignore
  585. at_rule_name.clear();
  586. state = State::Global;
  587. Log::Message(Log::LT_WARNING, "Invalid at-rule identifier '%s' found in stylesheet at %s:%d", at_rule_identifier.c_str(),
  588. stream_file_name.c_str(), line_number);
  589. }
  590. }
  591. else
  592. {
  593. Log::Message(Log::LT_WARNING, "Invalid character '%c' found while parsing at-rule identifier in stylesheet at %s:%d", token,
  594. stream_file_name.c_str(), line_number);
  595. state = State::Invalid;
  596. }
  597. }
  598. break;
  599. case State::KeyframeBlock:
  600. {
  601. if (token == '{')
  602. {
  603. // Initialize current block if not present
  604. if (!current_block.stylesheet)
  605. {
  606. current_block = {PropertyDictionary{}, UniquePtr<StyleSheet>(new StyleSheet()), MediaQueryModifier::None};
  607. }
  608. // Each keyframe in keyframes has its own block which is processed here
  609. PropertyDictionary properties;
  610. PropertySpecificationParser parser(properties, StyleSheetSpecification::GetPropertySpecification());
  611. ReadProperties(parser);
  612. if (!ParseKeyframeBlock(current_block.stylesheet->keyframes, at_rule_name, pre_token_str, properties))
  613. continue;
  614. }
  615. else if (token == '}')
  616. {
  617. at_rule_name.clear();
  618. state = State::Global;
  619. }
  620. else
  621. {
  622. Log::Message(Log::LT_WARNING, "Invalid character '%c' found while parsing keyframe block in stylesheet at %s:%d", token,
  623. stream_file_name.c_str(), line_number);
  624. state = State::Invalid;
  625. }
  626. }
  627. break;
  628. default:
  629. RMLUI_ERROR;
  630. state = State::Invalid;
  631. break;
  632. }
  633. if (state == State::Invalid)
  634. break;
  635. }
  636. if (state == State::Invalid)
  637. break;
  638. }
  639. // Complete last block if present
  640. if (current_block.stylesheet)
  641. {
  642. PostprocessKeyframes(current_block.stylesheet->keyframes);
  643. current_block.stylesheet->specificity_offset = rule_count;
  644. style_sheets.push_back(std::move(current_block));
  645. }
  646. return !style_sheets.empty();
  647. }
  648. void StyleSheetParser::ParseProperties(PropertyDictionary& parsed_properties, const String& properties)
  649. {
  650. RMLUI_ASSERT(!stream);
  651. StreamMemory stream_owner((const byte*)properties.c_str(), properties.size());
  652. stream = &stream_owner;
  653. PropertySpecificationParser parser(parsed_properties, StyleSheetSpecification::GetPropertySpecification());
  654. ReadProperties(parser);
  655. stream = nullptr;
  656. }
  657. StyleSheetNodeListRaw StyleSheetParser::ConstructNodes(StyleSheetNode& root_node, const String& selectors)
  658. {
  659. const PropertyDictionary empty_properties;
  660. StringList selector_list;
  661. StringUtilities::ExpandString(selector_list, selectors, ',', '(', ')');
  662. StyleSheetNodeListRaw leaf_nodes;
  663. for (const String& selector : selector_list)
  664. {
  665. StyleSheetNode* leaf_node = ImportProperties(&root_node, selector, empty_properties, 0);
  666. if (!leaf_node)
  667. Log::Message(Log::LT_WARNING, "Invalid selector '%s' encountered.", selector.c_str());
  668. else if (leaf_node != &root_node)
  669. leaf_nodes.push_back(leaf_node);
  670. }
  671. return leaf_nodes;
  672. }
  673. void StyleSheetParser::ReadProperties(AbstractPropertyParser& property_parser)
  674. {
  675. RMLUI_ZoneScoped;
  676. String name;
  677. String value;
  678. enum ParseState { NAME, VALUE, QUOTE };
  679. ParseState state = NAME;
  680. char character;
  681. char previous_character = 0;
  682. while (ReadCharacter(character))
  683. {
  684. parse_buffer_pos++;
  685. switch (state)
  686. {
  687. case NAME:
  688. {
  689. if (character == ';')
  690. {
  691. name = StringUtilities::StripWhitespace(name);
  692. if (!name.empty())
  693. {
  694. Log::Message(Log::LT_WARNING, "Found name with no value while parsing property declaration '%s' at %s:%d", name.c_str(),
  695. stream_file_name.c_str(), line_number);
  696. name.clear();
  697. }
  698. }
  699. else if (character == '}')
  700. {
  701. name = StringUtilities::StripWhitespace(name);
  702. if (!name.empty())
  703. Log::Message(Log::LT_WARNING, "End of rule encountered while parsing property declaration '%s' at %s:%d", name.c_str(),
  704. stream_file_name.c_str(), line_number);
  705. return;
  706. }
  707. else if (character == ':')
  708. {
  709. name = StringUtilities::StripWhitespace(name);
  710. state = VALUE;
  711. }
  712. else
  713. name += character;
  714. }
  715. break;
  716. case VALUE:
  717. {
  718. if (character == ';')
  719. {
  720. value = StringUtilities::StripWhitespace(value);
  721. if (!property_parser.Parse(name, value))
  722. Log::Message(Log::LT_WARNING, "Syntax error parsing property declaration '%s: %s;' in %s: %d.", name.c_str(), value.c_str(),
  723. stream_file_name.c_str(), line_number);
  724. name.clear();
  725. value.clear();
  726. state = NAME;
  727. }
  728. else if (character == '}')
  729. {
  730. break;
  731. }
  732. else
  733. {
  734. value += character;
  735. if (character == '"')
  736. state = QUOTE;
  737. }
  738. }
  739. break;
  740. case QUOTE:
  741. {
  742. value += character;
  743. if (character == '"' && previous_character != '\\')
  744. state = VALUE;
  745. }
  746. break;
  747. }
  748. if (character == '}')
  749. break;
  750. previous_character = character;
  751. }
  752. if (state == VALUE && !name.empty() && !value.empty())
  753. {
  754. value = StringUtilities::StripWhitespace(value);
  755. if (!property_parser.Parse(name, value))
  756. Log::Message(Log::LT_WARNING, "Syntax error parsing property declaration '%s: %s;' in %s: %d.", name.c_str(), value.c_str(),
  757. stream_file_name.c_str(), line_number);
  758. }
  759. else if (!StringUtilities::StripWhitespace(name).empty() || !value.empty())
  760. {
  761. Log::Message(Log::LT_WARNING, "Invalid property declaration '%s':'%s' at %s:%d", name.c_str(), value.c_str(), stream_file_name.c_str(),
  762. line_number);
  763. }
  764. }
  765. StyleSheetNode* StyleSheetParser::ImportProperties(StyleSheetNode* node, const String& rule, const PropertyDictionary& properties,
  766. int rule_specificity)
  767. {
  768. StyleSheetNode* leaf_node = node;
  769. // Create each node going down the tree.
  770. for (size_t index = 0; index < rule.size();)
  771. {
  772. CompoundSelector selector;
  773. // Determine the combinator connecting the previous node if any.
  774. for (; index > 0 && index < rule.size(); index++)
  775. {
  776. bool reached_end_of_combinators = false;
  777. switch (rule[index])
  778. {
  779. case ' ': break;
  780. case '>': selector.combinator = SelectorCombinator::Child; break;
  781. case '+': selector.combinator = SelectorCombinator::NextSibling; break;
  782. case '~': selector.combinator = SelectorCombinator::SubsequentSibling; break;
  783. default: reached_end_of_combinators = true; break;
  784. }
  785. if (reached_end_of_combinators)
  786. break;
  787. }
  788. // Determine the node's requirements.
  789. while (index < rule.size())
  790. {
  791. size_t start_index = index;
  792. size_t end_index = index + 1;
  793. if (rule[start_index] == '*')
  794. start_index += 1;
  795. if (rule[start_index] == '[')
  796. {
  797. end_index = rule.find(']', start_index + 1);
  798. if (end_index == String::npos)
  799. return nullptr;
  800. end_index += 1;
  801. }
  802. else
  803. {
  804. int parenthesis_count = 0;
  805. // Read until we hit the next identifier. Don't match inside parenthesis in case of structural selectors.
  806. for (; end_index < rule.size(); end_index++)
  807. {
  808. static const String identifiers = "#.:[ >+~";
  809. if (parenthesis_count == 0 && identifiers.find(rule[end_index]) != String::npos)
  810. break;
  811. if (rule[end_index] == '(')
  812. parenthesis_count += 1;
  813. else if (rule[end_index] == ')')
  814. parenthesis_count -= 1;
  815. }
  816. }
  817. if (end_index > start_index)
  818. {
  819. const char* p_begin = rule.data() + start_index;
  820. const char* p_end = rule.data() + end_index;
  821. switch (rule[start_index])
  822. {
  823. case '#': selector.id = String(p_begin + 1, p_end); break;
  824. case '.': selector.class_names.push_back(String(p_begin + 1, p_end)); break;
  825. case ':':
  826. {
  827. String pseudo_class_name = String(p_begin + 1, p_end);
  828. StructuralSelector node_selector = StyleSheetFactory::GetSelector(pseudo_class_name);
  829. if (node_selector.type != StructuralSelectorType::Invalid)
  830. selector.structural_selectors.push_back(node_selector);
  831. else
  832. selector.pseudo_class_names.push_back(std::move(pseudo_class_name));
  833. }
  834. break;
  835. case '[':
  836. {
  837. const size_t i_attr_begin = start_index + 1;
  838. const size_t i_attr_end = end_index - 1;
  839. if (i_attr_end <= i_attr_begin)
  840. return nullptr;
  841. AttributeSelector attribute;
  842. static const String attribute_operators = "=~|^$*]";
  843. size_t i_cursor = Math::Min(static_cast<size_t>(rule.find_first_of(attribute_operators, i_attr_begin)), i_attr_end);
  844. attribute.name = rule.substr(i_attr_begin, i_cursor - i_attr_begin);
  845. if (i_cursor < i_attr_end)
  846. {
  847. const char c = rule[i_cursor];
  848. attribute.type = AttributeSelectorType(c);
  849. // Move cursor past operator. Non-'=' symbols are always followed by '=' so move two characters.
  850. i_cursor += (c == '=' ? 1 : 2);
  851. size_t i_value_end = i_attr_end;
  852. if (i_cursor < i_attr_end && (rule[i_cursor] == '"' || rule[i_cursor] == '\''))
  853. {
  854. i_cursor += 1;
  855. i_value_end -= 1;
  856. }
  857. if (i_cursor < i_value_end)
  858. attribute.value = rule.substr(i_cursor, i_value_end - i_cursor);
  859. }
  860. selector.attributes.push_back(std::move(attribute));
  861. }
  862. break;
  863. default: selector.tag = String(p_begin, p_end); break;
  864. }
  865. }
  866. index = end_index;
  867. // If we reached a combinator then we submit the current node and start fresh with a new node.
  868. static const String combinators(" >+~");
  869. if (combinators.find(rule[index]) != String::npos)
  870. break;
  871. }
  872. // Sort the classes and pseudo-classes so they are consistent across equivalent declarations that shuffle the order around.
  873. std::sort(selector.class_names.begin(), selector.class_names.end());
  874. std::sort(selector.attributes.begin(), selector.attributes.end());
  875. std::sort(selector.pseudo_class_names.begin(), selector.pseudo_class_names.end());
  876. std::sort(selector.structural_selectors.begin(), selector.structural_selectors.end());
  877. // Add the new child node, or retrieve the existing child if we have an exact match.
  878. leaf_node = leaf_node->GetOrCreateChildNode(std::move(selector));
  879. }
  880. // Merge the new properties with those already on the leaf node.
  881. leaf_node->ImportProperties(properties, rule_specificity);
  882. return leaf_node;
  883. }
  884. char StyleSheetParser::FindAnyToken(String& buffer, const char* tokens)
  885. {
  886. buffer.clear();
  887. char character;
  888. while (ReadCharacter(character))
  889. {
  890. if (strchr(tokens, character) != nullptr)
  891. {
  892. parse_buffer_pos++;
  893. return character;
  894. }
  895. else
  896. {
  897. buffer += character;
  898. parse_buffer_pos++;
  899. }
  900. }
  901. return 0;
  902. }
  903. bool StyleSheetParser::ReadCharacter(char& buffer)
  904. {
  905. bool comment = false;
  906. // Continuously fill the buffer until either we run out of stream or we find the requested token.
  907. do
  908. {
  909. while (parse_buffer_pos < parse_buffer.size())
  910. {
  911. if (parse_buffer[parse_buffer_pos] == '\n')
  912. line_number++;
  913. else if (comment)
  914. {
  915. // Check for closing comment
  916. if (parse_buffer[parse_buffer_pos] == '*')
  917. {
  918. parse_buffer_pos++;
  919. if (parse_buffer_pos >= parse_buffer.size())
  920. {
  921. if (!FillBuffer())
  922. return false;
  923. }
  924. if (parse_buffer[parse_buffer_pos] == '/')
  925. comment = false;
  926. }
  927. }
  928. else
  929. {
  930. // Check for an opening comment
  931. if (parse_buffer[parse_buffer_pos] == '/')
  932. {
  933. parse_buffer_pos++;
  934. if (parse_buffer_pos >= parse_buffer.size())
  935. {
  936. if (!FillBuffer())
  937. {
  938. buffer = '/';
  939. parse_buffer = "/";
  940. return true;
  941. }
  942. }
  943. if (parse_buffer[parse_buffer_pos] == '*')
  944. comment = true;
  945. else
  946. {
  947. buffer = '/';
  948. if (parse_buffer_pos == 0)
  949. parse_buffer.insert(parse_buffer_pos, 1, '/');
  950. else
  951. parse_buffer_pos--;
  952. return true;
  953. }
  954. }
  955. if (!comment)
  956. {
  957. // If we find a character, return it
  958. buffer = parse_buffer[parse_buffer_pos];
  959. return true;
  960. }
  961. }
  962. parse_buffer_pos++;
  963. }
  964. } while (FillBuffer());
  965. return false;
  966. }
  967. bool StyleSheetParser::FillBuffer()
  968. {
  969. if (stream->IsEOS())
  970. return false;
  971. const bool first_read = parse_buffer.empty();
  972. // Read in some data (4092 instead of 4096 to avoid the buffer growing when we have to add back
  973. // a character after a failed comment parse.)
  974. parse_buffer.clear();
  975. bool read = stream->Read(parse_buffer, 4092) > 0;
  976. parse_buffer_pos = 0;
  977. if (first_read && parse_buffer.substr(0, 3) == "\xEF\xBB\xBF")
  978. {
  979. Log::Message(Log::LT_WARNING,
  980. "UTF-8 BOM encountered in stylesheet %s. This is not supported and can lead to subtle issues, "
  981. "please remove the BOM from the file's text encoding.",
  982. stream_file_name.c_str());
  983. }
  984. return read;
  985. }
  986. } // namespace Rml