StyleSheetParser.cpp 35 KB

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