StyleSheetParser.cpp 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154
  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. if (!ReadProperties(parser))
  332. return false;
  333. // Set non-defined properties to their defaults
  334. property_specification.SetPropertyDefaults(properties);
  335. properties.SetSourceOfAllProperties(source);
  336. named_decorator_map.emplace(name, NamedDecorator{std::move(decorator_type), decorator_instancer, std::move(properties)});
  337. return true;
  338. }
  339. bool StyleSheetParser::ParseMediaFeatureMap(const String& rules, PropertyDictionary& properties, MediaQueryModifier& modifier)
  340. {
  341. style_sheet_property_parsers->media_query.SetTargetProperties(&properties);
  342. enum ParseState { Global, Name, Value };
  343. ParseState state = Global;
  344. char character = 0;
  345. String name;
  346. String current_string;
  347. modifier = MediaQueryModifier::None;
  348. for (size_t cursor = 0; cursor < rules.length(); cursor++)
  349. {
  350. character = rules[cursor];
  351. switch (character)
  352. {
  353. case ' ':
  354. {
  355. if (state == Global)
  356. {
  357. current_string = StringUtilities::StripWhitespace(StringUtilities::ToLower(std::move(current_string)));
  358. if (current_string == "not")
  359. {
  360. // we can only ever see one "not" on the entire global query.
  361. if (modifier != MediaQueryModifier::None)
  362. {
  363. Log::Message(Log::LT_WARNING, "Unexpected '%s' in @media query list at %s:%d.", current_string.c_str(),
  364. stream_file_name.c_str(), line_number);
  365. return false;
  366. }
  367. modifier = MediaQueryModifier::Not;
  368. current_string.clear();
  369. }
  370. }
  371. break;
  372. }
  373. case '(':
  374. {
  375. if (state != Global)
  376. {
  377. Log::Message(Log::LT_WARNING, "Unexpected '(' in @media query list at %s:%d.", stream_file_name.c_str(), line_number);
  378. return false;
  379. }
  380. current_string = StringUtilities::StripWhitespace(StringUtilities::ToLower(std::move(current_string)));
  381. // allow an empty string to pass through only if we had just parsed a modifier.
  382. if (current_string != "and" && (properties.GetNumProperties() != 0 || !current_string.empty()))
  383. {
  384. Log::Message(Log::LT_WARNING, "Unexpected '%s' in @media query list at %s:%d. Expected 'and'.", current_string.c_str(),
  385. stream_file_name.c_str(), line_number);
  386. return false;
  387. }
  388. current_string.clear();
  389. state = Name;
  390. }
  391. break;
  392. case ')':
  393. {
  394. if (state != Value)
  395. {
  396. Log::Message(Log::LT_WARNING, "Unexpected ')' in @media query list at %s:%d.", stream_file_name.c_str(), line_number);
  397. return false;
  398. }
  399. current_string = StringUtilities::StripWhitespace(current_string);
  400. if (!style_sheet_property_parsers->media_query.Parse(name, current_string))
  401. Log::Message(Log::LT_WARNING, "Syntax error parsing media-query property declaration '%s: %s;' in %s: %d.", name.c_str(),
  402. current_string.c_str(), stream_file_name.c_str(), line_number);
  403. current_string.clear();
  404. state = Global;
  405. }
  406. break;
  407. case ':':
  408. {
  409. if (state != Name)
  410. {
  411. Log::Message(Log::LT_WARNING, "Unexpected ':' in @media query list at %s:%d.", stream_file_name.c_str(), line_number);
  412. return false;
  413. }
  414. current_string = StringUtilities::StripWhitespace(StringUtilities::ToLower(std::move(current_string)));
  415. if (!IsValidIdentifier(current_string))
  416. {
  417. Log::Message(Log::LT_WARNING, "Malformed property name '%s' in @media query list at %s:%d.", current_string.c_str(),
  418. stream_file_name.c_str(), line_number);
  419. return false;
  420. }
  421. name = current_string;
  422. current_string.clear();
  423. state = Value;
  424. }
  425. break;
  426. default: current_string += character;
  427. }
  428. }
  429. if (properties.GetNumProperties() == 0)
  430. {
  431. Log::Message(Log::LT_WARNING, "Media query list parsing yielded no properties at %s:%d.", stream_file_name.c_str(), line_number);
  432. }
  433. return true;
  434. }
  435. bool StyleSheetParser::Parse(MediaBlockList& style_sheets, Stream* _stream, int begin_line_number)
  436. {
  437. RMLUI_ZoneScoped;
  438. int rule_count = 0;
  439. line_number = begin_line_number;
  440. stream = _stream;
  441. stream_file_name = StringUtilities::Replace(stream->GetSourceURL().GetURL(), '|', ':');
  442. enum class State { Global, AtRuleIdentifier, KeyframeBlock, Invalid };
  443. State state = State::Global;
  444. MediaBlock current_block = {};
  445. // Need to track whether currently inside a nested media block or not, since the default scope is also a media block
  446. bool inside_media_block = false;
  447. // At-rules given by the following syntax in global space: @identifier name { block }
  448. String at_rule_name;
  449. // Look for more styles while data is available
  450. while (FillBuffer())
  451. {
  452. String pre_token_str;
  453. while (char token = FindToken(pre_token_str, "{@}", true))
  454. {
  455. switch (state)
  456. {
  457. case State::Global:
  458. {
  459. if (token == '{')
  460. {
  461. // Initialize current block if not present
  462. if (!current_block.stylesheet)
  463. {
  464. current_block = MediaBlock{PropertyDictionary{}, UniquePtr<StyleSheet>(new StyleSheet()), MediaQueryModifier::None};
  465. }
  466. const int rule_line_number = line_number;
  467. // Read the attributes
  468. PropertyDictionary properties;
  469. PropertySpecificationParser parser(properties, StyleSheetSpecification::GetPropertySpecification());
  470. if (!ReadProperties(parser))
  471. continue;
  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. if (!ReadProperties(parser))
  612. continue;
  613. if (!ParseKeyframeBlock(current_block.stylesheet->keyframes, at_rule_name, pre_token_str, properties))
  614. continue;
  615. }
  616. else if (token == '}')
  617. {
  618. at_rule_name.clear();
  619. state = State::Global;
  620. }
  621. else
  622. {
  623. Log::Message(Log::LT_WARNING, "Invalid character '%c' found while parsing keyframe block in stylesheet at %s:%d", token,
  624. stream_file_name.c_str(), line_number);
  625. state = State::Invalid;
  626. }
  627. }
  628. break;
  629. default:
  630. RMLUI_ERROR;
  631. state = State::Invalid;
  632. break;
  633. }
  634. if (state == State::Invalid)
  635. break;
  636. }
  637. if (state == State::Invalid)
  638. break;
  639. }
  640. // Complete last block if present
  641. if (current_block.stylesheet)
  642. {
  643. PostprocessKeyframes(current_block.stylesheet->keyframes);
  644. current_block.stylesheet->specificity_offset = rule_count;
  645. style_sheets.push_back(std::move(current_block));
  646. }
  647. return !style_sheets.empty();
  648. }
  649. bool StyleSheetParser::ParseProperties(PropertyDictionary& parsed_properties, const String& properties)
  650. {
  651. RMLUI_ASSERT(!stream);
  652. StreamMemory stream_owner((const byte*)properties.c_str(), properties.size());
  653. stream = &stream_owner;
  654. PropertySpecificationParser parser(parsed_properties, StyleSheetSpecification::GetPropertySpecification());
  655. bool success = ReadProperties(parser);
  656. stream = nullptr;
  657. return success;
  658. }
  659. StyleSheetNodeListRaw StyleSheetParser::ConstructNodes(StyleSheetNode& root_node, const String& selectors)
  660. {
  661. const PropertyDictionary empty_properties;
  662. StringList selector_list;
  663. StringUtilities::ExpandString(selector_list, selectors, ',', '(', ')');
  664. StyleSheetNodeListRaw leaf_nodes;
  665. for (const String& selector : selector_list)
  666. {
  667. StyleSheetNode* leaf_node = ImportProperties(&root_node, selector, empty_properties, 0);
  668. if (!leaf_node)
  669. Log::Message(Log::LT_WARNING, "Invalid selector '%s' encountered.", selector.c_str());
  670. else if (leaf_node != &root_node)
  671. leaf_nodes.push_back(leaf_node);
  672. }
  673. return leaf_nodes;
  674. }
  675. bool StyleSheetParser::ReadProperties(AbstractPropertyParser& property_parser)
  676. {
  677. RMLUI_ZoneScoped;
  678. String name;
  679. String value;
  680. enum ParseState { NAME, VALUE, QUOTE };
  681. ParseState state = NAME;
  682. char character;
  683. char previous_character = 0;
  684. while (ReadCharacter(character))
  685. {
  686. parse_buffer_pos++;
  687. switch (state)
  688. {
  689. case NAME:
  690. {
  691. if (character == ';')
  692. {
  693. name = StringUtilities::StripWhitespace(name);
  694. if (!name.empty())
  695. {
  696. Log::Message(Log::LT_WARNING, "Found name with no value while parsing property declaration '%s' at %s:%d", name.c_str(),
  697. stream_file_name.c_str(), line_number);
  698. name.clear();
  699. }
  700. }
  701. else if (character == '}')
  702. {
  703. name = StringUtilities::StripWhitespace(name);
  704. if (!name.empty())
  705. Log::Message(Log::LT_WARNING, "End of rule encountered while parsing property declaration '%s' at %s:%d", name.c_str(),
  706. stream_file_name.c_str(), line_number);
  707. return true;
  708. }
  709. else if (character == ':')
  710. {
  711. name = StringUtilities::StripWhitespace(name);
  712. state = VALUE;
  713. }
  714. else
  715. name += character;
  716. }
  717. break;
  718. case VALUE:
  719. {
  720. if (character == ';')
  721. {
  722. value = StringUtilities::StripWhitespace(value);
  723. if (!property_parser.Parse(name, value))
  724. Log::Message(Log::LT_WARNING, "Syntax error parsing property declaration '%s: %s;' in %s: %d.", name.c_str(), value.c_str(),
  725. stream_file_name.c_str(), line_number);
  726. name.clear();
  727. value.clear();
  728. state = NAME;
  729. }
  730. else if (character == '}')
  731. {
  732. break;
  733. }
  734. else
  735. {
  736. value += character;
  737. if (character == '"')
  738. state = QUOTE;
  739. }
  740. }
  741. break;
  742. case QUOTE:
  743. {
  744. value += character;
  745. if (character == '"' && previous_character != '\\')
  746. state = VALUE;
  747. }
  748. break;
  749. }
  750. if (character == '}')
  751. break;
  752. previous_character = character;
  753. }
  754. if (state == VALUE && !name.empty() && !value.empty())
  755. {
  756. value = StringUtilities::StripWhitespace(value);
  757. if (!property_parser.Parse(name, value))
  758. Log::Message(Log::LT_WARNING, "Syntax error parsing property declaration '%s: %s;' in %s: %d.", name.c_str(), value.c_str(),
  759. stream_file_name.c_str(), line_number);
  760. }
  761. else if (!StringUtilities::StripWhitespace(name).empty() || !value.empty())
  762. {
  763. Log::Message(Log::LT_WARNING, "Invalid property declaration '%s':'%s' at %s:%d", name.c_str(), value.c_str(), stream_file_name.c_str(),
  764. line_number);
  765. }
  766. return true;
  767. }
  768. StyleSheetNode* StyleSheetParser::ImportProperties(StyleSheetNode* node, const String& rule, const PropertyDictionary& properties,
  769. int rule_specificity)
  770. {
  771. StyleSheetNode* leaf_node = node;
  772. // Create each node going down the tree.
  773. for (size_t index = 0; index < rule.size();)
  774. {
  775. CompoundSelector selector;
  776. // Determine the combinator connecting the previous node if any.
  777. for (; index > 0 && index < rule.size(); index++)
  778. {
  779. bool reached_end_of_combinators = false;
  780. switch (rule[index])
  781. {
  782. case ' ': break;
  783. case '>': selector.combinator = SelectorCombinator::Child; break;
  784. case '+': selector.combinator = SelectorCombinator::NextSibling; break;
  785. case '~': selector.combinator = SelectorCombinator::SubsequentSibling; break;
  786. default: reached_end_of_combinators = true; break;
  787. }
  788. if (reached_end_of_combinators)
  789. break;
  790. }
  791. // Determine the node's requirements.
  792. while (index < rule.size())
  793. {
  794. size_t start_index = index;
  795. size_t end_index = index + 1;
  796. if (rule[start_index] == '*')
  797. start_index += 1;
  798. if (rule[start_index] == '[')
  799. {
  800. end_index = rule.find(']', start_index + 1);
  801. if (end_index == String::npos)
  802. return nullptr;
  803. end_index += 1;
  804. }
  805. else
  806. {
  807. int parenthesis_count = 0;
  808. // Read until we hit the next identifier. Don't match inside parenthesis in case of structural selectors.
  809. for (; end_index < rule.size(); end_index++)
  810. {
  811. static const String identifiers = "#.:[ >+~";
  812. if (parenthesis_count == 0 && identifiers.find(rule[end_index]) != String::npos)
  813. break;
  814. if (rule[end_index] == '(')
  815. parenthesis_count += 1;
  816. else if (rule[end_index] == ')')
  817. parenthesis_count -= 1;
  818. }
  819. }
  820. if (end_index > start_index)
  821. {
  822. const char* p_begin = rule.data() + start_index;
  823. const char* p_end = rule.data() + end_index;
  824. switch (rule[start_index])
  825. {
  826. case '#': selector.id = String(p_begin + 1, p_end); break;
  827. case '.': selector.class_names.push_back(String(p_begin + 1, p_end)); break;
  828. case ':':
  829. {
  830. String pseudo_class_name = String(p_begin + 1, p_end);
  831. StructuralSelector node_selector = StyleSheetFactory::GetSelector(pseudo_class_name);
  832. if (node_selector.type != StructuralSelectorType::Invalid)
  833. selector.structural_selectors.push_back(node_selector);
  834. else
  835. selector.pseudo_class_names.push_back(std::move(pseudo_class_name));
  836. }
  837. break;
  838. case '[':
  839. {
  840. const size_t i_attr_begin = start_index + 1;
  841. const size_t i_attr_end = end_index - 1;
  842. if (i_attr_end <= i_attr_begin)
  843. return nullptr;
  844. AttributeSelector attribute;
  845. static const String attribute_operators = "=~|^$*]";
  846. size_t i_cursor = Math::Min(static_cast<size_t>(rule.find_first_of(attribute_operators, i_attr_begin)), i_attr_end);
  847. attribute.name = rule.substr(i_attr_begin, i_cursor - i_attr_begin);
  848. if (i_cursor < i_attr_end)
  849. {
  850. const char c = rule[i_cursor];
  851. attribute.type = AttributeSelectorType(c);
  852. // Move cursor past operator. Non-'=' symbols are always followed by '=' so move two characters.
  853. i_cursor += (c == '=' ? 1 : 2);
  854. size_t i_value_end = i_attr_end;
  855. if (i_cursor < i_attr_end && (rule[i_cursor] == '"' || rule[i_cursor] == '\''))
  856. {
  857. i_cursor += 1;
  858. i_value_end -= 1;
  859. }
  860. if (i_cursor < i_value_end)
  861. attribute.value = rule.substr(i_cursor, i_value_end - i_cursor);
  862. }
  863. selector.attributes.push_back(std::move(attribute));
  864. }
  865. break;
  866. default: selector.tag = String(p_begin, p_end); break;
  867. }
  868. }
  869. index = end_index;
  870. // If we reached a combinator then we submit the current node and start fresh with a new node.
  871. static const String combinators(" >+~");
  872. if (combinators.find(rule[index]) != String::npos)
  873. break;
  874. }
  875. // Sort the classes and pseudo-classes so they are consistent across equivalent declarations that shuffle the order around.
  876. std::sort(selector.class_names.begin(), selector.class_names.end());
  877. std::sort(selector.attributes.begin(), selector.attributes.end());
  878. std::sort(selector.pseudo_class_names.begin(), selector.pseudo_class_names.end());
  879. std::sort(selector.structural_selectors.begin(), selector.structural_selectors.end());
  880. // Add the new child node, or retrieve the existing child if we have an exact match.
  881. leaf_node = leaf_node->GetOrCreateChildNode(std::move(selector));
  882. }
  883. // Merge the new properties with those already on the leaf node.
  884. leaf_node->ImportProperties(properties, rule_specificity);
  885. return leaf_node;
  886. }
  887. char StyleSheetParser::FindToken(String& buffer, const char* tokens, bool remove_token)
  888. {
  889. buffer.clear();
  890. char character;
  891. while (ReadCharacter(character))
  892. {
  893. if (strchr(tokens, character) != nullptr)
  894. {
  895. if (remove_token)
  896. parse_buffer_pos++;
  897. return character;
  898. }
  899. else
  900. {
  901. buffer += character;
  902. parse_buffer_pos++;
  903. }
  904. }
  905. return 0;
  906. }
  907. bool StyleSheetParser::ReadCharacter(char& buffer)
  908. {
  909. bool comment = false;
  910. // Continuously fill the buffer until either we run out of
  911. // stream or we find the requested token
  912. do
  913. {
  914. while (parse_buffer_pos < parse_buffer.size())
  915. {
  916. if (parse_buffer[parse_buffer_pos] == '\n')
  917. line_number++;
  918. else if (comment)
  919. {
  920. // Check for closing comment
  921. if (parse_buffer[parse_buffer_pos] == '*')
  922. {
  923. parse_buffer_pos++;
  924. if (parse_buffer_pos >= parse_buffer.size())
  925. {
  926. if (!FillBuffer())
  927. return false;
  928. }
  929. if (parse_buffer[parse_buffer_pos] == '/')
  930. comment = false;
  931. }
  932. }
  933. else
  934. {
  935. // Check for an opening comment
  936. if (parse_buffer[parse_buffer_pos] == '/')
  937. {
  938. parse_buffer_pos++;
  939. if (parse_buffer_pos >= parse_buffer.size())
  940. {
  941. if (!FillBuffer())
  942. {
  943. buffer = '/';
  944. parse_buffer = "/";
  945. return true;
  946. }
  947. }
  948. if (parse_buffer[parse_buffer_pos] == '*')
  949. comment = true;
  950. else
  951. {
  952. buffer = '/';
  953. if (parse_buffer_pos == 0)
  954. parse_buffer.insert(parse_buffer_pos, 1, '/');
  955. else
  956. parse_buffer_pos--;
  957. return true;
  958. }
  959. }
  960. if (!comment)
  961. {
  962. // If we find a character, return it
  963. buffer = parse_buffer[parse_buffer_pos];
  964. return true;
  965. }
  966. }
  967. parse_buffer_pos++;
  968. }
  969. } while (FillBuffer());
  970. return false;
  971. }
  972. bool StyleSheetParser::FillBuffer()
  973. {
  974. // If theres no data to process, abort
  975. if (stream->IsEOS())
  976. return false;
  977. // Read in some data (4092 instead of 4096 to avoid the buffer growing when we have to add back
  978. // a character after a failed comment parse.)
  979. parse_buffer.clear();
  980. bool read = stream->Read(parse_buffer, 4092) > 0;
  981. parse_buffer_pos = 0;
  982. return read;
  983. }
  984. } // namespace Rml