StyleSheetParser.cpp 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145
  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. stream_file_name = StringUtilities::Replace(stream->GetSourceURL().GetURL(), '|', ':');
  441. enum class State { Global, AtRuleIdentifier, KeyframeBlock, Invalid };
  442. State state = State::Global;
  443. MediaBlock current_block = {};
  444. // Need to track whether currently inside a nested media block or not, since the default scope is also a media block
  445. bool inside_media_block = false;
  446. // At-rules given by the following syntax in global space: @identifier name { block }
  447. String at_rule_name;
  448. // Look for more styles while data is available
  449. while (FillBuffer())
  450. {
  451. String pre_token_str;
  452. while (char token = FindAnyToken(pre_token_str, "{@}"))
  453. {
  454. switch (state)
  455. {
  456. case State::Global:
  457. {
  458. if (token == '{')
  459. {
  460. // Initialize current block if not present
  461. if (!current_block.stylesheet)
  462. {
  463. current_block = MediaBlock{PropertyDictionary{}, UniquePtr<StyleSheet>(new StyleSheet()), MediaQueryModifier::None};
  464. }
  465. const int rule_line_number = line_number;
  466. // Read the attributes
  467. PropertyDictionary properties;
  468. PropertySpecificationParser parser(properties, StyleSheetSpecification::GetPropertySpecification());
  469. ReadProperties(parser);
  470. StringList rule_name_list;
  471. StringUtilities::ExpandString(rule_name_list, pre_token_str, ',', '(', ')');
  472. // Add style nodes to the root of the tree
  473. for (size_t i = 0; i < rule_name_list.size(); i++)
  474. {
  475. auto source = MakeShared<PropertySource>(stream_file_name, rule_line_number, rule_name_list[i]);
  476. properties.SetSourceOfAllProperties(source);
  477. if (!ImportProperties(current_block.stylesheet->root.get(), rule_name_list[i], properties, rule_count))
  478. {
  479. Log::Message(Log::LT_WARNING, "Invalid selector '%s' encountered while parsing stylesheet at %s:%d.",
  480. rule_name_list[i].c_str(), stream_file_name.c_str(), line_number);
  481. }
  482. }
  483. rule_count++;
  484. }
  485. else if (token == '@')
  486. {
  487. state = State::AtRuleIdentifier;
  488. }
  489. else if (inside_media_block && token == '}')
  490. {
  491. // Complete current block
  492. PostprocessKeyframes(current_block.stylesheet->keyframes);
  493. current_block.stylesheet->specificity_offset = rule_count;
  494. style_sheets.push_back(std::move(current_block));
  495. current_block = {};
  496. inside_media_block = false;
  497. break;
  498. }
  499. else
  500. {
  501. Log::Message(Log::LT_WARNING, "Invalid character '%c' found while parsing stylesheet at %s:%d. Trying to proceed.", token,
  502. stream_file_name.c_str(), line_number);
  503. }
  504. }
  505. break;
  506. case State::AtRuleIdentifier:
  507. {
  508. if (token == '{')
  509. {
  510. // Initialize current block if not present
  511. if (!current_block.stylesheet)
  512. {
  513. current_block = {PropertyDictionary{}, UniquePtr<StyleSheet>(new StyleSheet()), MediaQueryModifier::None};
  514. }
  515. const String at_rule_identifier = StringUtilities::StripWhitespace(pre_token_str.substr(0, pre_token_str.find(' ')));
  516. at_rule_name = StringUtilities::StripWhitespace(pre_token_str.substr(at_rule_identifier.size()));
  517. if (at_rule_identifier == "keyframes")
  518. {
  519. state = State::KeyframeBlock;
  520. }
  521. else if (at_rule_identifier == "decorator")
  522. {
  523. auto source = MakeShared<PropertySource>(stream_file_name, (int)line_number, pre_token_str);
  524. ParseDecoratorBlock(at_rule_name, current_block.stylesheet->named_decorator_map, source);
  525. at_rule_name.clear();
  526. state = State::Global;
  527. }
  528. else if (at_rule_identifier == "spritesheet")
  529. {
  530. auto& spritesheet_property_parser = style_sheet_property_parsers->spritesheet;
  531. ReadProperties(spritesheet_property_parser);
  532. const String& image_source = spritesheet_property_parser.GetImageSource();
  533. const SpriteDefinitionList& sprite_definitions = spritesheet_property_parser.GetSpriteDefinitions();
  534. const float image_resolution_factor = spritesheet_property_parser.GetImageResolutionFactor();
  535. if (sprite_definitions.empty())
  536. {
  537. Log::Message(Log::LT_WARNING, "Spritesheet '%s' has no sprites defined, ignored. At %s:%d", at_rule_name.c_str(),
  538. stream_file_name.c_str(), line_number);
  539. }
  540. else if (image_source.empty())
  541. {
  542. Log::Message(Log::LT_WARNING, "No image source (property 'src') specified for spritesheet '%s'. At %s:%d",
  543. at_rule_name.c_str(), stream_file_name.c_str(), line_number);
  544. }
  545. else if (image_resolution_factor <= 0.0f || image_resolution_factor >= 100.f)
  546. {
  547. Log::Message(Log::LT_WARNING,
  548. "Spritesheet resolution (property 'resolution') value must be larger than 0.0 and smaller than 100.0, given %g. In "
  549. "spritesheet '%s'. At %s:%d",
  550. image_resolution_factor, at_rule_name.c_str(), stream_file_name.c_str(), line_number);
  551. }
  552. else
  553. {
  554. const float display_scale = 1.0f / image_resolution_factor;
  555. current_block.stylesheet->spritesheet_list.AddSpriteSheet(at_rule_name, image_source, stream_file_name, (int)line_number,
  556. display_scale, sprite_definitions);
  557. }
  558. spritesheet_property_parser.Clear();
  559. at_rule_name.clear();
  560. state = State::Global;
  561. }
  562. else if (at_rule_identifier == "media")
  563. {
  564. // complete the current "global" block if present and start a new block
  565. if (current_block.stylesheet)
  566. {
  567. PostprocessKeyframes(current_block.stylesheet->keyframes);
  568. current_block.stylesheet->specificity_offset = rule_count;
  569. style_sheets.push_back(std::move(current_block));
  570. current_block = {};
  571. }
  572. // parse media query list into block
  573. PropertyDictionary feature_map;
  574. MediaQueryModifier modifier;
  575. ParseMediaFeatureMap(at_rule_name, feature_map, modifier);
  576. current_block = {std::move(feature_map), UniquePtr<StyleSheet>(new StyleSheet()), modifier};
  577. inside_media_block = true;
  578. state = State::Global;
  579. }
  580. else
  581. {
  582. // Invalid identifier, should ignore
  583. at_rule_name.clear();
  584. state = State::Global;
  585. Log::Message(Log::LT_WARNING, "Invalid at-rule identifier '%s' found in stylesheet at %s:%d", at_rule_identifier.c_str(),
  586. stream_file_name.c_str(), line_number);
  587. }
  588. }
  589. else
  590. {
  591. Log::Message(Log::LT_WARNING, "Invalid character '%c' found while parsing at-rule identifier in stylesheet at %s:%d", token,
  592. stream_file_name.c_str(), line_number);
  593. state = State::Invalid;
  594. }
  595. }
  596. break;
  597. case State::KeyframeBlock:
  598. {
  599. if (token == '{')
  600. {
  601. // Initialize current block if not present
  602. if (!current_block.stylesheet)
  603. {
  604. current_block = {PropertyDictionary{}, UniquePtr<StyleSheet>(new StyleSheet()), MediaQueryModifier::None};
  605. }
  606. // Each keyframe in keyframes has its own block which is processed here
  607. PropertyDictionary properties;
  608. PropertySpecificationParser parser(properties, StyleSheetSpecification::GetPropertySpecification());
  609. ReadProperties(parser);
  610. if (!ParseKeyframeBlock(current_block.stylesheet->keyframes, at_rule_name, pre_token_str, properties))
  611. continue;
  612. }
  613. else if (token == '}')
  614. {
  615. at_rule_name.clear();
  616. state = State::Global;
  617. }
  618. else
  619. {
  620. Log::Message(Log::LT_WARNING, "Invalid character '%c' found while parsing keyframe block in stylesheet at %s:%d", token,
  621. stream_file_name.c_str(), line_number);
  622. state = State::Invalid;
  623. }
  624. }
  625. break;
  626. default:
  627. RMLUI_ERROR;
  628. state = State::Invalid;
  629. break;
  630. }
  631. if (state == State::Invalid)
  632. break;
  633. }
  634. if (state == State::Invalid)
  635. break;
  636. }
  637. // Complete last block if present
  638. if (current_block.stylesheet)
  639. {
  640. PostprocessKeyframes(current_block.stylesheet->keyframes);
  641. current_block.stylesheet->specificity_offset = rule_count;
  642. style_sheets.push_back(std::move(current_block));
  643. }
  644. return !style_sheets.empty();
  645. }
  646. void StyleSheetParser::ParseProperties(PropertyDictionary& parsed_properties, const String& properties)
  647. {
  648. RMLUI_ASSERT(!stream);
  649. StreamMemory stream_owner((const byte*)properties.c_str(), properties.size());
  650. stream = &stream_owner;
  651. PropertySpecificationParser parser(parsed_properties, StyleSheetSpecification::GetPropertySpecification());
  652. ReadProperties(parser);
  653. stream = nullptr;
  654. }
  655. StyleSheetNodeListRaw StyleSheetParser::ConstructNodes(StyleSheetNode& root_node, const String& selectors)
  656. {
  657. const PropertyDictionary empty_properties;
  658. StringList selector_list;
  659. StringUtilities::ExpandString(selector_list, selectors, ',', '(', ')');
  660. StyleSheetNodeListRaw leaf_nodes;
  661. for (const String& selector : selector_list)
  662. {
  663. StyleSheetNode* leaf_node = ImportProperties(&root_node, selector, empty_properties, 0);
  664. if (!leaf_node)
  665. Log::Message(Log::LT_WARNING, "Invalid selector '%s' encountered.", selector.c_str());
  666. else if (leaf_node != &root_node)
  667. leaf_nodes.push_back(leaf_node);
  668. }
  669. return leaf_nodes;
  670. }
  671. void StyleSheetParser::ReadProperties(AbstractPropertyParser& property_parser)
  672. {
  673. RMLUI_ZoneScoped;
  674. String name;
  675. String value;
  676. enum ParseState { NAME, VALUE, QUOTE };
  677. ParseState state = NAME;
  678. char character;
  679. char previous_character = 0;
  680. while (ReadCharacter(character))
  681. {
  682. parse_buffer_pos++;
  683. switch (state)
  684. {
  685. case NAME:
  686. {
  687. if (character == ';')
  688. {
  689. name = StringUtilities::StripWhitespace(name);
  690. if (!name.empty())
  691. {
  692. Log::Message(Log::LT_WARNING, "Found name with no value while parsing property declaration '%s' at %s:%d", name.c_str(),
  693. stream_file_name.c_str(), line_number);
  694. name.clear();
  695. }
  696. }
  697. else if (character == '}')
  698. {
  699. name = StringUtilities::StripWhitespace(name);
  700. if (!name.empty())
  701. Log::Message(Log::LT_WARNING, "End of rule encountered while parsing property declaration '%s' at %s:%d", name.c_str(),
  702. stream_file_name.c_str(), line_number);
  703. return;
  704. }
  705. else if (character == ':')
  706. {
  707. name = StringUtilities::StripWhitespace(name);
  708. state = VALUE;
  709. }
  710. else
  711. name += character;
  712. }
  713. break;
  714. case VALUE:
  715. {
  716. if (character == ';')
  717. {
  718. value = StringUtilities::StripWhitespace(value);
  719. if (!property_parser.Parse(name, value))
  720. Log::Message(Log::LT_WARNING, "Syntax error parsing property declaration '%s: %s;' in %s: %d.", name.c_str(), value.c_str(),
  721. stream_file_name.c_str(), line_number);
  722. name.clear();
  723. value.clear();
  724. state = NAME;
  725. }
  726. else if (character == '}')
  727. {
  728. break;
  729. }
  730. else
  731. {
  732. value += character;
  733. if (character == '"')
  734. state = QUOTE;
  735. }
  736. }
  737. break;
  738. case QUOTE:
  739. {
  740. value += character;
  741. if (character == '"' && previous_character != '\\')
  742. state = VALUE;
  743. }
  744. break;
  745. }
  746. if (character == '}')
  747. break;
  748. previous_character = character;
  749. }
  750. if (state == VALUE && !name.empty() && !value.empty())
  751. {
  752. value = StringUtilities::StripWhitespace(value);
  753. if (!property_parser.Parse(name, value))
  754. Log::Message(Log::LT_WARNING, "Syntax error parsing property declaration '%s: %s;' in %s: %d.", name.c_str(), value.c_str(),
  755. stream_file_name.c_str(), line_number);
  756. }
  757. else if (!StringUtilities::StripWhitespace(name).empty() || !value.empty())
  758. {
  759. Log::Message(Log::LT_WARNING, "Invalid property declaration '%s':'%s' at %s:%d", name.c_str(), value.c_str(), stream_file_name.c_str(),
  760. line_number);
  761. }
  762. }
  763. StyleSheetNode* StyleSheetParser::ImportProperties(StyleSheetNode* node, const String& rule, const PropertyDictionary& properties,
  764. int rule_specificity)
  765. {
  766. StyleSheetNode* leaf_node = node;
  767. // Create each node going down the tree.
  768. for (size_t index = 0; index < rule.size();)
  769. {
  770. CompoundSelector selector;
  771. // Determine the combinator connecting the previous node if any.
  772. for (; index > 0 && index < rule.size(); index++)
  773. {
  774. bool reached_end_of_combinators = false;
  775. switch (rule[index])
  776. {
  777. case ' ': break;
  778. case '>': selector.combinator = SelectorCombinator::Child; break;
  779. case '+': selector.combinator = SelectorCombinator::NextSibling; break;
  780. case '~': selector.combinator = SelectorCombinator::SubsequentSibling; break;
  781. default: reached_end_of_combinators = true; break;
  782. }
  783. if (reached_end_of_combinators)
  784. break;
  785. }
  786. // Determine the node's requirements.
  787. while (index < rule.size())
  788. {
  789. size_t start_index = index;
  790. size_t end_index = index + 1;
  791. if (rule[start_index] == '*')
  792. start_index += 1;
  793. if (rule[start_index] == '[')
  794. {
  795. end_index = rule.find(']', start_index + 1);
  796. if (end_index == String::npos)
  797. return nullptr;
  798. end_index += 1;
  799. }
  800. else
  801. {
  802. int parenthesis_count = 0;
  803. // Read until we hit the next identifier. Don't match inside parenthesis in case of structural selectors.
  804. for (; end_index < rule.size(); end_index++)
  805. {
  806. static const String identifiers = "#.:[ >+~";
  807. if (parenthesis_count == 0 && identifiers.find(rule[end_index]) != String::npos)
  808. break;
  809. if (rule[end_index] == '(')
  810. parenthesis_count += 1;
  811. else if (rule[end_index] == ')')
  812. parenthesis_count -= 1;
  813. }
  814. }
  815. if (end_index > start_index)
  816. {
  817. const char* p_begin = rule.data() + start_index;
  818. const char* p_end = rule.data() + end_index;
  819. switch (rule[start_index])
  820. {
  821. case '#': selector.id = String(p_begin + 1, p_end); break;
  822. case '.': selector.class_names.push_back(String(p_begin + 1, p_end)); break;
  823. case ':':
  824. {
  825. String pseudo_class_name = String(p_begin + 1, p_end);
  826. StructuralSelector node_selector = StyleSheetFactory::GetSelector(pseudo_class_name);
  827. if (node_selector.type != StructuralSelectorType::Invalid)
  828. selector.structural_selectors.push_back(node_selector);
  829. else
  830. selector.pseudo_class_names.push_back(std::move(pseudo_class_name));
  831. }
  832. break;
  833. case '[':
  834. {
  835. const size_t i_attr_begin = start_index + 1;
  836. const size_t i_attr_end = end_index - 1;
  837. if (i_attr_end <= i_attr_begin)
  838. return nullptr;
  839. AttributeSelector attribute;
  840. static const String attribute_operators = "=~|^$*]";
  841. size_t i_cursor = Math::Min(static_cast<size_t>(rule.find_first_of(attribute_operators, i_attr_begin)), i_attr_end);
  842. attribute.name = rule.substr(i_attr_begin, i_cursor - i_attr_begin);
  843. if (i_cursor < i_attr_end)
  844. {
  845. const char c = rule[i_cursor];
  846. attribute.type = AttributeSelectorType(c);
  847. // Move cursor past operator. Non-'=' symbols are always followed by '=' so move two characters.
  848. i_cursor += (c == '=' ? 1 : 2);
  849. size_t i_value_end = i_attr_end;
  850. if (i_cursor < i_attr_end && (rule[i_cursor] == '"' || rule[i_cursor] == '\''))
  851. {
  852. i_cursor += 1;
  853. i_value_end -= 1;
  854. }
  855. if (i_cursor < i_value_end)
  856. attribute.value = rule.substr(i_cursor, i_value_end - i_cursor);
  857. }
  858. selector.attributes.push_back(std::move(attribute));
  859. }
  860. break;
  861. default: selector.tag = String(p_begin, p_end); break;
  862. }
  863. }
  864. index = end_index;
  865. // If we reached a combinator then we submit the current node and start fresh with a new node.
  866. static const String combinators(" >+~");
  867. if (combinators.find(rule[index]) != String::npos)
  868. break;
  869. }
  870. // Sort the classes and pseudo-classes so they are consistent across equivalent declarations that shuffle the order around.
  871. std::sort(selector.class_names.begin(), selector.class_names.end());
  872. std::sort(selector.attributes.begin(), selector.attributes.end());
  873. std::sort(selector.pseudo_class_names.begin(), selector.pseudo_class_names.end());
  874. std::sort(selector.structural_selectors.begin(), selector.structural_selectors.end());
  875. // Add the new child node, or retrieve the existing child if we have an exact match.
  876. leaf_node = leaf_node->GetOrCreateChildNode(std::move(selector));
  877. }
  878. // Merge the new properties with those already on the leaf node.
  879. leaf_node->ImportProperties(properties, rule_specificity);
  880. return leaf_node;
  881. }
  882. char StyleSheetParser::FindAnyToken(String& buffer, const char* tokens)
  883. {
  884. buffer.clear();
  885. char character;
  886. while (ReadCharacter(character))
  887. {
  888. if (strchr(tokens, character) != nullptr)
  889. {
  890. parse_buffer_pos++;
  891. return character;
  892. }
  893. else
  894. {
  895. buffer += character;
  896. parse_buffer_pos++;
  897. }
  898. }
  899. return 0;
  900. }
  901. bool StyleSheetParser::ReadCharacter(char& buffer)
  902. {
  903. bool comment = false;
  904. // Continuously fill the buffer until either we run out of stream or we find the requested token.
  905. do
  906. {
  907. while (parse_buffer_pos < parse_buffer.size())
  908. {
  909. if (parse_buffer[parse_buffer_pos] == '\n')
  910. line_number++;
  911. else if (comment)
  912. {
  913. // Check for closing comment
  914. if (parse_buffer[parse_buffer_pos] == '*')
  915. {
  916. parse_buffer_pos++;
  917. if (parse_buffer_pos >= parse_buffer.size())
  918. {
  919. if (!FillBuffer())
  920. return false;
  921. }
  922. if (parse_buffer[parse_buffer_pos] == '/')
  923. comment = false;
  924. }
  925. }
  926. else
  927. {
  928. // Check for an opening comment
  929. if (parse_buffer[parse_buffer_pos] == '/')
  930. {
  931. parse_buffer_pos++;
  932. if (parse_buffer_pos >= parse_buffer.size())
  933. {
  934. if (!FillBuffer())
  935. {
  936. buffer = '/';
  937. parse_buffer = "/";
  938. return true;
  939. }
  940. }
  941. if (parse_buffer[parse_buffer_pos] == '*')
  942. comment = true;
  943. else
  944. {
  945. buffer = '/';
  946. if (parse_buffer_pos == 0)
  947. parse_buffer.insert(parse_buffer_pos, 1, '/');
  948. else
  949. parse_buffer_pos--;
  950. return true;
  951. }
  952. }
  953. if (!comment)
  954. {
  955. // If we find a character, return it
  956. buffer = parse_buffer[parse_buffer_pos];
  957. return true;
  958. }
  959. }
  960. parse_buffer_pos++;
  961. }
  962. } while (FillBuffer());
  963. return false;
  964. }
  965. bool StyleSheetParser::FillBuffer()
  966. {
  967. if (stream->IsEOS())
  968. return false;
  969. // Read in some data (4092 instead of 4096 to avoid the buffer growing when we have to add back
  970. // a character after a failed comment parse.)
  971. parse_buffer.clear();
  972. bool read = stream->Read(parse_buffer, 4092) > 0;
  973. parse_buffer_pos = 0;
  974. return read;
  975. }
  976. } // namespace Rml