StyleSheetParser.cpp 36 KB

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