StyleSheetParser.cpp 35 KB

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