StyleSheetParser.cpp 34 KB

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