StyleSheetParser.cpp 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151
  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 "StyleSheetFactory.h"
  41. #include "StyleSheetNode.h"
  42. #include <algorithm>
  43. #include <string.h>
  44. namespace Rml {
  45. class AbstractPropertyParser : NonCopyMoveable {
  46. protected:
  47. ~AbstractPropertyParser() = default;
  48. public:
  49. virtual bool Parse(const String& name, const String& value) = 0;
  50. };
  51. /*
  52. * PropertySpecificationParser just passes the parsing to a property specification. Usually
  53. * the main stylesheet specification, except for e.g. @decorator blocks.
  54. */
  55. class PropertySpecificationParser final : public AbstractPropertyParser {
  56. private:
  57. // The dictionary to store the properties in.
  58. PropertyDictionary& properties;
  59. // The specification used to parse the values. Normally the default stylesheet specification, but not for e.g. all at-rules such as decorators.
  60. const PropertySpecification& specification;
  61. public:
  62. PropertySpecificationParser(PropertyDictionary& properties, const PropertySpecification& specification) :
  63. properties(properties), specification(specification)
  64. {}
  65. bool Parse(const String& name, const String& value) override { return specification.ParsePropertyDeclaration(properties, name, value); }
  66. };
  67. /*
  68. * Spritesheets need a special parser because its property names are arbitrary keys,
  69. * while its values are always rectangles. Thus, it must be parsed with a special "rectangle" parser
  70. * for every name-value pair. We can probably optimize this for @performance.
  71. */
  72. class SpritesheetPropertyParser final : public AbstractPropertyParser {
  73. private:
  74. String image_source;
  75. float image_resolution_factor = 1.f;
  76. SpriteDefinitionList sprite_definitions;
  77. PropertyDictionary properties;
  78. PropertySpecification specification;
  79. PropertyId id_src, id_rx, id_ry, id_rw, id_rh, id_resolution;
  80. ShorthandId id_rectangle;
  81. public:
  82. SpritesheetPropertyParser() : specification(4, 1)
  83. {
  84. id_src = specification.RegisterProperty("src", "", false, false).AddParser("string").GetId();
  85. id_rx = specification.RegisterProperty("rectangle-x", "", false, false).AddParser("length").GetId();
  86. id_ry = specification.RegisterProperty("rectangle-y", "", false, false).AddParser("length").GetId();
  87. id_rw = specification.RegisterProperty("rectangle-w", "", false, false).AddParser("length").GetId();
  88. id_rh = specification.RegisterProperty("rectangle-h", "", false, false).AddParser("length").GetId();
  89. id_rectangle = specification.RegisterShorthand("rectangle", "rectangle-x, rectangle-y, rectangle-w, rectangle-h", ShorthandType::FallThrough);
  90. id_resolution = specification.RegisterProperty("resolution", "", false, false).AddParser("resolution").GetId();
  91. }
  92. const String& GetImageSource() const { return image_source; }
  93. const SpriteDefinitionList& GetSpriteDefinitions() const { return sprite_definitions; }
  94. float GetImageResolutionFactor() const { return image_resolution_factor; }
  95. void Clear()
  96. {
  97. image_resolution_factor = 1.f;
  98. image_source.clear();
  99. sprite_definitions.clear();
  100. }
  101. bool Parse(const String& name, const String& value) override
  102. {
  103. if (name == "src")
  104. {
  105. if (!specification.ParsePropertyDeclaration(properties, id_src, value))
  106. return false;
  107. if (const Property* property = properties.GetProperty(id_src))
  108. {
  109. if (property->unit == Unit::STRING)
  110. image_source = property->Get<String>();
  111. }
  112. }
  113. else if (name == "resolution")
  114. {
  115. if (!specification.ParsePropertyDeclaration(properties, id_resolution, value))
  116. return false;
  117. if (const Property* property = properties.GetProperty(id_resolution))
  118. {
  119. if (property->unit == Unit::X)
  120. image_resolution_factor = property->Get<float>();
  121. }
  122. }
  123. else
  124. {
  125. if (!specification.ParseShorthandDeclaration(properties, id_rectangle, value))
  126. return false;
  127. Vector2f position, size;
  128. if (auto p = properties.GetProperty(id_rx))
  129. position.x = p->Get<float>();
  130. if (auto p = properties.GetProperty(id_ry))
  131. position.y = p->Get<float>();
  132. if (auto p = properties.GetProperty(id_rw))
  133. size.x = p->Get<float>();
  134. if (auto p = properties.GetProperty(id_rh))
  135. size.y = p->Get<float>();
  136. sprite_definitions.emplace_back(name, Rectanglef::FromPositionSize(position, size));
  137. }
  138. return true;
  139. }
  140. };
  141. static UniquePtr<SpritesheetPropertyParser> spritesheet_property_parser;
  142. /*
  143. * Media queries need a special parser because they have unique properties that
  144. * aren't admissible in other property declaration contexts.
  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. static UniquePtr<MediaQueryPropertyParser> media_query_property_parser;
  180. StyleSheetParser::StyleSheetParser()
  181. {
  182. line_number = 0;
  183. stream = nullptr;
  184. parse_buffer_pos = 0;
  185. }
  186. StyleSheetParser::~StyleSheetParser() {}
  187. void StyleSheetParser::Initialise()
  188. {
  189. spritesheet_property_parser = MakeUnique<SpritesheetPropertyParser>();
  190. media_query_property_parser = MakeUnique<MediaQueryPropertyParser>();
  191. }
  192. void StyleSheetParser::Shutdown()
  193. {
  194. spritesheet_property_parser.reset();
  195. media_query_property_parser.reset();
  196. }
  197. static bool IsValidIdentifier(const String& str)
  198. {
  199. if (str.empty())
  200. return false;
  201. for (size_t i = 0; i < str.size(); i++)
  202. {
  203. char c = str[i];
  204. bool valid = ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c == '-') || (c == '_'));
  205. if (!valid)
  206. return false;
  207. }
  208. return true;
  209. }
  210. static void PostprocessKeyframes(KeyframesMap& keyframes_map)
  211. {
  212. for (auto& keyframes_pair : keyframes_map)
  213. {
  214. Keyframes& keyframes = keyframes_pair.second;
  215. auto& blocks = keyframes.blocks;
  216. auto& property_ids = keyframes.property_ids;
  217. // Sort keyframes on selector value.
  218. std::sort(blocks.begin(), blocks.end(), [](const KeyframeBlock& a, const KeyframeBlock& b) { return a.normalized_time < b.normalized_time; });
  219. // Add all property names specified by any block
  220. if (blocks.size() > 0)
  221. property_ids.reserve(blocks.size() * blocks[0].properties.GetNumProperties());
  222. for (auto& block : blocks)
  223. {
  224. for (auto& property : block.properties.GetProperties())
  225. property_ids.push_back(property.first);
  226. }
  227. // Remove duplicate property names
  228. std::sort(property_ids.begin(), property_ids.end());
  229. property_ids.erase(std::unique(property_ids.begin(), property_ids.end()), property_ids.end());
  230. property_ids.shrink_to_fit();
  231. }
  232. }
  233. bool StyleSheetParser::ParseKeyframeBlock(KeyframesMap& keyframes_map, const String& identifier, const String& rules,
  234. const PropertyDictionary& properties)
  235. {
  236. if (!IsValidIdentifier(identifier))
  237. {
  238. Log::Message(Log::LT_WARNING, "Invalid keyframes identifier '%s' at %s:%d", identifier.c_str(), stream_file_name.c_str(), line_number);
  239. return false;
  240. }
  241. if (properties.GetNumProperties() == 0)
  242. return true;
  243. StringList rule_list;
  244. StringUtilities::ExpandString(rule_list, rules);
  245. Vector<float> rule_values;
  246. rule_values.reserve(rule_list.size());
  247. for (auto rule : rule_list)
  248. {
  249. float value = 0.0f;
  250. int count = 0;
  251. rule = StringUtilities::ToLower(std::move(rule));
  252. if (rule == "from")
  253. rule_values.push_back(0.0f);
  254. else if (rule == "to")
  255. rule_values.push_back(1.0f);
  256. else if (sscanf(rule.c_str(), "%f%%%n", &value, &count) == 1)
  257. if (count > 0 && value >= 0.0f && value <= 100.0f)
  258. rule_values.push_back(0.01f * value);
  259. }
  260. if (rule_values.empty())
  261. {
  262. Log::Message(Log::LT_WARNING, "Invalid keyframes rule(s) '%s' at %s:%d", rules.c_str(), stream_file_name.c_str(), line_number);
  263. return false;
  264. }
  265. Keyframes& keyframes = keyframes_map[identifier];
  266. for (float selector : rule_values)
  267. {
  268. auto it = std::find_if(keyframes.blocks.begin(), keyframes.blocks.end(),
  269. [selector](const KeyframeBlock& keyframe_block) { return Math::Absolute(keyframe_block.normalized_time - selector) < 0.0001f; });
  270. if (it == keyframes.blocks.end())
  271. {
  272. keyframes.blocks.emplace_back(selector);
  273. it = (keyframes.blocks.end() - 1);
  274. }
  275. else
  276. {
  277. // In case of duplicate keyframes, we only use the latest definition as per CSS rules
  278. it->properties = PropertyDictionary();
  279. }
  280. it->properties.Import(properties);
  281. }
  282. return true;
  283. }
  284. bool StyleSheetParser::ParseDecoratorBlock(const String& at_name, NamedDecoratorMap& named_decorator_map,
  285. const SharedPtr<const PropertySource>& source)
  286. {
  287. StringList name_type;
  288. StringUtilities::ExpandString(name_type, at_name, ':');
  289. if (name_type.size() != 2 || name_type[0].empty() || name_type[1].empty())
  290. {
  291. Log::Message(Log::LT_WARNING, "Decorator syntax error at %s:%d. Use syntax: '@decorator name : type { ... }'.", stream_file_name.c_str(),
  292. line_number);
  293. return false;
  294. }
  295. const String& name = name_type[0];
  296. String decorator_type = name_type[1];
  297. auto it_find = named_decorator_map.find(name);
  298. if (it_find != named_decorator_map.end())
  299. {
  300. Log::Message(Log::LT_WARNING, "Decorator with name '%s' already declared, ignoring decorator at %s:%d.", name.c_str(),
  301. stream_file_name.c_str(), line_number);
  302. return false;
  303. }
  304. // Get the instancer associated with the decorator type
  305. DecoratorInstancer* decorator_instancer = Factory::GetDecoratorInstancer(decorator_type);
  306. PropertyDictionary properties;
  307. if (!decorator_instancer)
  308. {
  309. // Type is not a declared decorator type, instead, see if it is another decorator name, then we inherit its properties.
  310. auto it = named_decorator_map.find(decorator_type);
  311. if (it != named_decorator_map.end())
  312. {
  313. // Yes, try to retrieve the instancer from the parent type, and add its property values.
  314. decorator_instancer = Factory::GetDecoratorInstancer(it->second.type);
  315. properties = it->second.properties;
  316. decorator_type = it->second.type;
  317. }
  318. // If we still don't have an instancer, we cannot continue.
  319. if (!decorator_instancer)
  320. {
  321. Log::Message(Log::LT_WARNING, "Invalid decorator type '%s' declared at %s:%d.", decorator_type.c_str(), stream_file_name.c_str(),
  322. line_number);
  323. return false;
  324. }
  325. }
  326. const PropertySpecification& property_specification = decorator_instancer->GetPropertySpecification();
  327. PropertySpecificationParser parser(properties, property_specification);
  328. if (!ReadProperties(parser))
  329. return false;
  330. // Set non-defined properties to their defaults
  331. property_specification.SetPropertyDefaults(properties);
  332. properties.SetSourceOfAllProperties(source);
  333. named_decorator_map.emplace(name, NamedDecorator{std::move(decorator_type), decorator_instancer, std::move(properties)});
  334. return true;
  335. }
  336. bool StyleSheetParser::ParseMediaFeatureMap(const String& rules, PropertyDictionary& properties, MediaQueryModifier& modifier)
  337. {
  338. media_query_property_parser->SetTargetProperties(&properties);
  339. enum ParseState { Global, Name, Value };
  340. ParseState state = Global;
  341. char character = 0;
  342. String name;
  343. String current_string;
  344. modifier = MediaQueryModifier::None;
  345. for (size_t cursor = 0; cursor < rules.length(); cursor++)
  346. {
  347. character = rules[cursor];
  348. switch (character)
  349. {
  350. case ' ':
  351. {
  352. if (state == Global)
  353. {
  354. current_string = StringUtilities::StripWhitespace(StringUtilities::ToLower(std::move(current_string)));
  355. if (current_string == "not")
  356. {
  357. // we can only ever see one "not" on the entire global query.
  358. if (modifier != MediaQueryModifier::None)
  359. {
  360. Log::Message(Log::LT_WARNING, "Unexpected '%s' in @media query list at %s:%d.", current_string.c_str(), stream_file_name.c_str(), line_number);
  361. return false;
  362. }
  363. modifier = MediaQueryModifier::Not;
  364. current_string.clear();
  365. }
  366. }
  367. break;
  368. }
  369. case '(':
  370. {
  371. if (state != Global)
  372. {
  373. Log::Message(Log::LT_WARNING, "Unexpected '(' in @media query list at %s:%d.", stream_file_name.c_str(), line_number);
  374. return false;
  375. }
  376. current_string = StringUtilities::StripWhitespace(StringUtilities::ToLower(std::move(current_string)));
  377. // allow an empty string to pass through only if we had just parsed a modifier.
  378. if (current_string != "and" &&
  379. (properties.GetNumProperties() != 0 || !current_string.empty()))
  380. {
  381. Log::Message(Log::LT_WARNING, "Unexpected '%s' in @media query list at %s:%d. Expected 'and'.", current_string.c_str(),
  382. stream_file_name.c_str(), line_number);
  383. return false;
  384. }
  385. current_string.clear();
  386. state = Name;
  387. }
  388. break;
  389. case ')':
  390. {
  391. if (state != Value)
  392. {
  393. Log::Message(Log::LT_WARNING, "Unexpected ')' in @media query list at %s:%d.", stream_file_name.c_str(), line_number);
  394. return false;
  395. }
  396. current_string = StringUtilities::StripWhitespace(current_string);
  397. if (!media_query_property_parser->Parse(name, current_string))
  398. Log::Message(Log::LT_WARNING, "Syntax error parsing media-query property declaration '%s: %s;' in %s: %d.", name.c_str(),
  399. current_string.c_str(), stream_file_name.c_str(), line_number);
  400. current_string.clear();
  401. state = Global;
  402. }
  403. break;
  404. case ':':
  405. {
  406. if (state != Name)
  407. {
  408. Log::Message(Log::LT_WARNING, "Unexpected ':' in @media query list at %s:%d.", stream_file_name.c_str(), line_number);
  409. return false;
  410. }
  411. current_string = StringUtilities::StripWhitespace(StringUtilities::ToLower(std::move(current_string)));
  412. if (!IsValidIdentifier(current_string))
  413. {
  414. Log::Message(Log::LT_WARNING, "Malformed property name '%s' in @media query list at %s:%d.", current_string.c_str(),
  415. stream_file_name.c_str(), line_number);
  416. return false;
  417. }
  418. name = current_string;
  419. current_string.clear();
  420. state = Value;
  421. }
  422. break;
  423. default: current_string += character;
  424. }
  425. }
  426. if (properties.GetNumProperties() == 0)
  427. {
  428. Log::Message(Log::LT_WARNING, "Media query list parsing yielded no properties at %s:%d.", stream_file_name.c_str(), line_number);
  429. }
  430. return true;
  431. }
  432. bool StyleSheetParser::Parse(MediaBlockList& style_sheets, Stream* _stream, int begin_line_number)
  433. {
  434. RMLUI_ZoneScoped;
  435. int rule_count = 0;
  436. line_number = begin_line_number;
  437. stream = _stream;
  438. stream_file_name = StringUtilities::Replace(stream->GetSourceURL().GetURL(), '|', ':');
  439. enum class State { Global, AtRuleIdentifier, KeyframeBlock, Invalid };
  440. State state = State::Global;
  441. MediaBlock current_block = {};
  442. // Need to track whether currently inside a nested media block or not, since the default scope is also a media block
  443. bool inside_media_block = false;
  444. // At-rules given by the following syntax in global space: @identifier name { block }
  445. String at_rule_name;
  446. // Look for more styles while data is available
  447. while (FillBuffer())
  448. {
  449. String pre_token_str;
  450. while (char token = FindToken(pre_token_str, "{@}", true))
  451. {
  452. switch (state)
  453. {
  454. case State::Global:
  455. {
  456. if (token == '{')
  457. {
  458. // Initialize current block if not present
  459. if (!current_block.stylesheet)
  460. {
  461. current_block = MediaBlock{PropertyDictionary{}, UniquePtr<StyleSheet>(new StyleSheet()), MediaQueryModifier::None};
  462. }
  463. const int rule_line_number = line_number;
  464. // Read the attributes
  465. PropertyDictionary properties;
  466. PropertySpecificationParser parser(properties, StyleSheetSpecification::GetPropertySpecification());
  467. if (!ReadProperties(parser))
  468. continue;
  469. StringList rule_name_list;
  470. StringUtilities::ExpandString(rule_name_list, pre_token_str, ',', '(', ')');
  471. // Add style nodes to the root of the tree
  472. for (size_t i = 0; i < rule_name_list.size(); i++)
  473. {
  474. auto source = MakeShared<PropertySource>(stream_file_name, rule_line_number, rule_name_list[i]);
  475. properties.SetSourceOfAllProperties(source);
  476. if (!ImportProperties(current_block.stylesheet->root.get(), rule_name_list[i], properties, rule_count))
  477. {
  478. Log::Message(Log::LT_WARNING, "Invalid selector '%s' encountered while parsing stylesheet at %s:%d.",
  479. rule_name_list[i].c_str(), stream_file_name.c_str(), line_number);
  480. }
  481. }
  482. rule_count++;
  483. }
  484. else if (token == '@')
  485. {
  486. state = State::AtRuleIdentifier;
  487. }
  488. else if (inside_media_block && token == '}')
  489. {
  490. // Complete current block
  491. PostprocessKeyframes(current_block.stylesheet->keyframes);
  492. current_block.stylesheet->specificity_offset = rule_count;
  493. style_sheets.push_back(std::move(current_block));
  494. current_block = {};
  495. inside_media_block = false;
  496. break;
  497. }
  498. else
  499. {
  500. Log::Message(Log::LT_WARNING, "Invalid character '%c' found while parsing stylesheet at %s:%d. Trying to proceed.", token,
  501. stream_file_name.c_str(), line_number);
  502. }
  503. }
  504. break;
  505. case State::AtRuleIdentifier:
  506. {
  507. if (token == '{')
  508. {
  509. // Initialize current block if not present
  510. if (!current_block.stylesheet)
  511. {
  512. current_block = {PropertyDictionary{}, UniquePtr<StyleSheet>(new StyleSheet()), MediaQueryModifier::None};
  513. }
  514. const String at_rule_identifier = StringUtilities::StripWhitespace(pre_token_str.substr(0, pre_token_str.find(' ')));
  515. at_rule_name = StringUtilities::StripWhitespace(pre_token_str.substr(at_rule_identifier.size()));
  516. if (at_rule_identifier == "keyframes")
  517. {
  518. state = State::KeyframeBlock;
  519. }
  520. else if (at_rule_identifier == "decorator")
  521. {
  522. auto source = MakeShared<PropertySource>(stream_file_name, (int)line_number, pre_token_str);
  523. ParseDecoratorBlock(at_rule_name, current_block.stylesheet->named_decorator_map, source);
  524. at_rule_name.clear();
  525. state = State::Global;
  526. }
  527. else if (at_rule_identifier == "spritesheet")
  528. {
  529. // The spritesheet parser is reasonably heavy to initialize, so we make it a static global.
  530. ReadProperties(*spritesheet_property_parser);
  531. const String& image_source = spritesheet_property_parser->GetImageSource();
  532. const SpriteDefinitionList& sprite_definitions = spritesheet_property_parser->GetSpriteDefinitions();
  533. const float image_resolution_factor = spritesheet_property_parser->GetImageResolutionFactor();
  534. if (sprite_definitions.empty())
  535. {
  536. Log::Message(Log::LT_WARNING, "Spritesheet '%s' has no sprites defined, ignored. At %s:%d", at_rule_name.c_str(),
  537. stream_file_name.c_str(), line_number);
  538. }
  539. else if (image_source.empty())
  540. {
  541. Log::Message(Log::LT_WARNING, "No image source (property 'src') specified for spritesheet '%s'. At %s:%d",
  542. at_rule_name.c_str(), stream_file_name.c_str(), line_number);
  543. }
  544. else if (image_resolution_factor <= 0.0f || image_resolution_factor >= 100.f)
  545. {
  546. Log::Message(Log::LT_WARNING,
  547. "Spritesheet resolution (property 'resolution') value must be larger than 0.0 and smaller than 100.0, given %g. In "
  548. "spritesheet '%s'. At %s:%d",
  549. image_resolution_factor, at_rule_name.c_str(), stream_file_name.c_str(), line_number);
  550. }
  551. else
  552. {
  553. const float display_scale = 1.0f / image_resolution_factor;
  554. current_block.stylesheet->spritesheet_list.AddSpriteSheet(at_rule_name, image_source, stream_file_name, (int)line_number,
  555. display_scale, sprite_definitions);
  556. }
  557. spritesheet_property_parser->Clear();
  558. at_rule_name.clear();
  559. state = State::Global;
  560. }
  561. else if (at_rule_identifier == "media")
  562. {
  563. // complete the current "global" block if present and start a new block
  564. if (current_block.stylesheet)
  565. {
  566. PostprocessKeyframes(current_block.stylesheet->keyframes);
  567. current_block.stylesheet->specificity_offset = rule_count;
  568. style_sheets.push_back(std::move(current_block));
  569. current_block = {};
  570. }
  571. // parse media query list into block
  572. PropertyDictionary feature_map;
  573. MediaQueryModifier modifier;
  574. ParseMediaFeatureMap(at_rule_name, feature_map, modifier);
  575. current_block = {std::move(feature_map), UniquePtr<StyleSheet>(new StyleSheet()), modifier};
  576. inside_media_block = true;
  577. state = State::Global;
  578. }
  579. else
  580. {
  581. // Invalid identifier, should ignore
  582. at_rule_name.clear();
  583. state = State::Global;
  584. Log::Message(Log::LT_WARNING, "Invalid at-rule identifier '%s' found in stylesheet at %s:%d", at_rule_identifier.c_str(),
  585. stream_file_name.c_str(), line_number);
  586. }
  587. }
  588. else
  589. {
  590. Log::Message(Log::LT_WARNING, "Invalid character '%c' found while parsing at-rule identifier in stylesheet at %s:%d", token,
  591. stream_file_name.c_str(), line_number);
  592. state = State::Invalid;
  593. }
  594. }
  595. break;
  596. case State::KeyframeBlock:
  597. {
  598. if (token == '{')
  599. {
  600. // Initialize current block if not present
  601. if (!current_block.stylesheet)
  602. {
  603. current_block = {PropertyDictionary{}, UniquePtr<StyleSheet>(new StyleSheet()), MediaQueryModifier::None};
  604. }
  605. // Each keyframe in keyframes has its own block which is processed here
  606. PropertyDictionary properties;
  607. PropertySpecificationParser parser(properties, StyleSheetSpecification::GetPropertySpecification());
  608. if (!ReadProperties(parser))
  609. continue;
  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. bool 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. bool success = ReadProperties(parser);
  653. stream = nullptr;
  654. return success;
  655. }
  656. StyleSheetNodeListRaw StyleSheetParser::ConstructNodes(StyleSheetNode& root_node, const String& selectors)
  657. {
  658. const PropertyDictionary empty_properties;
  659. StringList selector_list;
  660. StringUtilities::ExpandString(selector_list, selectors, ',', '(', ')');
  661. StyleSheetNodeListRaw leaf_nodes;
  662. for (const String& selector : selector_list)
  663. {
  664. StyleSheetNode* leaf_node = ImportProperties(&root_node, selector, empty_properties, 0);
  665. if (!leaf_node)
  666. Log::Message(Log::LT_WARNING, "Invalid selector '%s' encountered.", selector.c_str());
  667. else if (leaf_node != &root_node)
  668. leaf_nodes.push_back(leaf_node);
  669. }
  670. return leaf_nodes;
  671. }
  672. bool StyleSheetParser::ReadProperties(AbstractPropertyParser& property_parser)
  673. {
  674. RMLUI_ZoneScoped;
  675. String name;
  676. String value;
  677. enum ParseState { NAME, VALUE, QUOTE };
  678. ParseState state = NAME;
  679. char character;
  680. char previous_character = 0;
  681. while (ReadCharacter(character))
  682. {
  683. parse_buffer_pos++;
  684. switch (state)
  685. {
  686. case NAME:
  687. {
  688. if (character == ';')
  689. {
  690. name = StringUtilities::StripWhitespace(name);
  691. if (!name.empty())
  692. {
  693. Log::Message(Log::LT_WARNING, "Found name with no value while parsing property declaration '%s' at %s:%d", name.c_str(),
  694. stream_file_name.c_str(), line_number);
  695. name.clear();
  696. }
  697. }
  698. else if (character == '}')
  699. {
  700. name = StringUtilities::StripWhitespace(name);
  701. if (!name.empty())
  702. Log::Message(Log::LT_WARNING, "End of rule encountered while parsing property declaration '%s' at %s:%d", name.c_str(),
  703. stream_file_name.c_str(), line_number);
  704. return true;
  705. }
  706. else if (character == ':')
  707. {
  708. name = StringUtilities::StripWhitespace(name);
  709. state = VALUE;
  710. }
  711. else
  712. name += character;
  713. }
  714. break;
  715. case VALUE:
  716. {
  717. if (character == ';')
  718. {
  719. value = StringUtilities::StripWhitespace(value);
  720. if (!property_parser.Parse(name, value))
  721. Log::Message(Log::LT_WARNING, "Syntax error parsing property declaration '%s: %s;' in %s: %d.", name.c_str(), value.c_str(),
  722. stream_file_name.c_str(), line_number);
  723. name.clear();
  724. value.clear();
  725. state = NAME;
  726. }
  727. else if (character == '}')
  728. {
  729. break;
  730. }
  731. else
  732. {
  733. value += character;
  734. if (character == '"')
  735. state = QUOTE;
  736. }
  737. }
  738. break;
  739. case QUOTE:
  740. {
  741. value += character;
  742. if (character == '"' && previous_character != '\\')
  743. state = VALUE;
  744. }
  745. break;
  746. }
  747. if (character == '}')
  748. break;
  749. previous_character = character;
  750. }
  751. if (state == VALUE && !name.empty() && !value.empty())
  752. {
  753. value = StringUtilities::StripWhitespace(value);
  754. if (!property_parser.Parse(name, value))
  755. Log::Message(Log::LT_WARNING, "Syntax error parsing property declaration '%s: %s;' in %s: %d.", name.c_str(), value.c_str(),
  756. stream_file_name.c_str(), line_number);
  757. }
  758. else if (!StringUtilities::StripWhitespace(name).empty() || !value.empty())
  759. {
  760. Log::Message(Log::LT_WARNING, "Invalid property declaration '%s':'%s' at %s:%d", name.c_str(), value.c_str(), stream_file_name.c_str(),
  761. line_number);
  762. }
  763. return true;
  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::FindToken(String& buffer, const char* tokens, bool remove_token)
  885. {
  886. buffer.clear();
  887. char character;
  888. while (ReadCharacter(character))
  889. {
  890. if (strchr(tokens, character) != nullptr)
  891. {
  892. if (remove_token)
  893. parse_buffer_pos++;
  894. return character;
  895. }
  896. else
  897. {
  898. buffer += character;
  899. parse_buffer_pos++;
  900. }
  901. }
  902. return 0;
  903. }
  904. bool StyleSheetParser::ReadCharacter(char& buffer)
  905. {
  906. bool comment = false;
  907. // Continuously fill the buffer until either we run out of
  908. // stream or we find the requested token
  909. do
  910. {
  911. while (parse_buffer_pos < parse_buffer.size())
  912. {
  913. if (parse_buffer[parse_buffer_pos] == '\n')
  914. line_number++;
  915. else if (comment)
  916. {
  917. // Check for closing comment
  918. if (parse_buffer[parse_buffer_pos] == '*')
  919. {
  920. parse_buffer_pos++;
  921. if (parse_buffer_pos >= parse_buffer.size())
  922. {
  923. if (!FillBuffer())
  924. return false;
  925. }
  926. if (parse_buffer[parse_buffer_pos] == '/')
  927. comment = false;
  928. }
  929. }
  930. else
  931. {
  932. // Check for an opening comment
  933. if (parse_buffer[parse_buffer_pos] == '/')
  934. {
  935. parse_buffer_pos++;
  936. if (parse_buffer_pos >= parse_buffer.size())
  937. {
  938. if (!FillBuffer())
  939. {
  940. buffer = '/';
  941. parse_buffer = "/";
  942. return true;
  943. }
  944. }
  945. if (parse_buffer[parse_buffer_pos] == '*')
  946. comment = true;
  947. else
  948. {
  949. buffer = '/';
  950. if (parse_buffer_pos == 0)
  951. parse_buffer.insert(parse_buffer_pos, 1, '/');
  952. else
  953. parse_buffer_pos--;
  954. return true;
  955. }
  956. }
  957. if (!comment)
  958. {
  959. // If we find a character, return it
  960. buffer = parse_buffer[parse_buffer_pos];
  961. return true;
  962. }
  963. }
  964. parse_buffer_pos++;
  965. }
  966. } while (FillBuffer());
  967. return false;
  968. }
  969. bool StyleSheetParser::FillBuffer()
  970. {
  971. // If theres no data to process, abort
  972. if (stream->IsEOS())
  973. return false;
  974. // Read in some data (4092 instead of 4096 to avoid the buffer growing when we have to add back
  975. // a character after a failed comment parse.)
  976. parse_buffer.clear();
  977. bool read = stream->Read(parse_buffer, 4092) > 0;
  978. parse_buffer_pos = 0;
  979. return read;
  980. }
  981. } // namespace Rml