PropertySpecification.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  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 "../../Include/RmlUi/Core/PropertySpecification.h"
  29. #include "../../Include/RmlUi/Core/Debug.h"
  30. #include "../../Include/RmlUi/Core/Log.h"
  31. #include "../../Include/RmlUi/Core/Profiling.h"
  32. #include "../../Include/RmlUi/Core/PropertyDefinition.h"
  33. #include "../../Include/RmlUi/Core/PropertyDictionary.h"
  34. #include "IdNameMap.h"
  35. #include "PropertyShorthandDefinition.h"
  36. #include <algorithm>
  37. #include <limits.h>
  38. #include <stdint.h>
  39. namespace Rml {
  40. PropertySpecification::PropertySpecification(size_t reserve_num_properties, size_t reserve_num_shorthands) :
  41. // Increment reserve numbers by one because the 'invalid' property occupies the first element
  42. properties(reserve_num_properties + 1), shorthands(reserve_num_shorthands + 1),
  43. property_map(MakeUnique<PropertyIdNameMap>(reserve_num_properties + 1)), shorthand_map(MakeUnique<ShorthandIdNameMap>(reserve_num_shorthands + 1))
  44. {}
  45. PropertySpecification::~PropertySpecification() {}
  46. PropertyDefinition& PropertySpecification::RegisterProperty(const String& property_name, const String& default_value, bool inherited,
  47. bool forces_layout, PropertyId id)
  48. {
  49. if (id == PropertyId::Invalid)
  50. id = property_map->GetOrCreateId(property_name);
  51. else
  52. property_map->AddPair(id, property_name);
  53. size_t index = (size_t)id;
  54. if (index >= size_t(PropertyId::MaxNumIds))
  55. {
  56. Log::Message(Log::LT_ERROR,
  57. "Fatal error while registering property '%s': Maximum number of allowed properties exceeded. Continuing execution may lead to crash.",
  58. property_name.c_str());
  59. RMLUI_ERROR;
  60. return *properties[0];
  61. }
  62. if (index < properties.size())
  63. {
  64. // We don't want to owerwrite an existing entry.
  65. if (properties[index])
  66. {
  67. Log::Message(Log::LT_ERROR, "While registering property '%s': The property is already registered.", property_name.c_str());
  68. return *properties[index];
  69. }
  70. }
  71. else
  72. {
  73. // Resize vector to hold the new index
  74. properties.resize((index * 3) / 2 + 1);
  75. }
  76. // Create and insert the new property
  77. properties[index] = MakeUnique<PropertyDefinition>(id, default_value, inherited, forces_layout);
  78. property_ids.Insert(id);
  79. if (inherited)
  80. property_ids_inherited.Insert(id);
  81. if (forces_layout)
  82. property_ids_forcing_layout.Insert(id);
  83. return *properties[index];
  84. }
  85. const PropertyDefinition* PropertySpecification::GetProperty(PropertyId id) const
  86. {
  87. if (id == PropertyId::Invalid || (size_t)id >= properties.size())
  88. return nullptr;
  89. return properties[(size_t)id].get();
  90. }
  91. const PropertyDefinition* PropertySpecification::GetProperty(const String& property_name) const
  92. {
  93. return GetProperty(property_map->GetId(property_name));
  94. }
  95. const PropertyIdSet& PropertySpecification::GetRegisteredProperties() const
  96. {
  97. return property_ids;
  98. }
  99. const PropertyIdSet& PropertySpecification::GetRegisteredInheritedProperties() const
  100. {
  101. return property_ids_inherited;
  102. }
  103. const PropertyIdSet& PropertySpecification::GetRegisteredPropertiesForcingLayout() const
  104. {
  105. return property_ids_forcing_layout;
  106. }
  107. ShorthandId PropertySpecification::RegisterShorthand(const String& shorthand_name, const String& property_names, ShorthandType type, ShorthandId id)
  108. {
  109. if (id == ShorthandId::Invalid)
  110. id = shorthand_map->GetOrCreateId(shorthand_name);
  111. else
  112. shorthand_map->AddPair(id, shorthand_name);
  113. StringList property_list;
  114. StringUtilities::ExpandString(property_list, StringUtilities::ToLower(property_names));
  115. // Construct the new shorthand definition and resolve its properties.
  116. UniquePtr<ShorthandDefinition> property_shorthand(new ShorthandDefinition());
  117. for (const String& raw_name : property_list)
  118. {
  119. ShorthandItem item;
  120. bool optional = false;
  121. bool repeats = false;
  122. String name = raw_name;
  123. if (!raw_name.empty() && raw_name.back() == '?')
  124. {
  125. optional = true;
  126. name.pop_back();
  127. }
  128. if (!raw_name.empty() && raw_name.back() == '#')
  129. {
  130. repeats = true;
  131. name.pop_back();
  132. }
  133. PropertyId property_id = property_map->GetId(name);
  134. if (property_id != PropertyId::Invalid)
  135. {
  136. // We have a valid property
  137. if (const PropertyDefinition* property = GetProperty(property_id))
  138. item = ShorthandItem(property_id, property, optional, repeats);
  139. }
  140. else
  141. {
  142. // Otherwise, we must be a shorthand
  143. ShorthandId shorthand_id = shorthand_map->GetId(name);
  144. // Test for valid shorthand id. The recursive types (and only those) can hold other shorthands.
  145. if (shorthand_id != ShorthandId::Invalid && (type == ShorthandType::RecursiveRepeat || type == ShorthandType::RecursiveCommaSeparated))
  146. {
  147. if (const ShorthandDefinition* shorthand = GetShorthand(shorthand_id))
  148. item = ShorthandItem(shorthand_id, shorthand, optional, repeats);
  149. }
  150. }
  151. if (item.type == ShorthandItemType::Invalid)
  152. {
  153. Log::Message(Log::LT_ERROR, "Shorthand property '%s' was registered with invalid property '%s'.", shorthand_name.c_str(), name.c_str());
  154. return ShorthandId::Invalid;
  155. }
  156. property_shorthand->items.push_back(item);
  157. }
  158. property_shorthand->id = id;
  159. property_shorthand->type = type;
  160. const size_t index = (size_t)id;
  161. if (index >= size_t(ShorthandId::MaxNumIds))
  162. {
  163. Log::Message(Log::LT_ERROR, "Error while registering shorthand '%s': Maximum number of allowed shorthands exceeded.", shorthand_name.c_str());
  164. return ShorthandId::Invalid;
  165. }
  166. if (index < shorthands.size())
  167. {
  168. // We don't want to owerwrite an existing entry.
  169. if (shorthands[index])
  170. {
  171. Log::Message(Log::LT_ERROR, "The shorthand '%s' already exists, ignoring.", shorthand_name.c_str());
  172. return ShorthandId::Invalid;
  173. }
  174. }
  175. else
  176. {
  177. // Resize vector to hold the new index
  178. shorthands.resize((index * 3) / 2 + 1);
  179. }
  180. shorthands[index] = std::move(property_shorthand);
  181. return id;
  182. }
  183. const ShorthandDefinition* PropertySpecification::GetShorthand(ShorthandId id) const
  184. {
  185. if (id == ShorthandId::Invalid || (size_t)id >= shorthands.size())
  186. return nullptr;
  187. return shorthands[(size_t)id].get();
  188. }
  189. const ShorthandDefinition* PropertySpecification::GetShorthand(const String& shorthand_name) const
  190. {
  191. return GetShorthand(shorthand_map->GetId(shorthand_name));
  192. }
  193. bool PropertySpecification::ParsePropertyDeclaration(PropertyDictionary& dictionary, const String& property_name, const String& property_value) const
  194. {
  195. RMLUI_ZoneScoped;
  196. // Try as a property first
  197. PropertyId property_id = property_map->GetId(property_name);
  198. if (property_id != PropertyId::Invalid)
  199. return ParsePropertyDeclaration(dictionary, property_id, property_value);
  200. // Then, as a shorthand
  201. ShorthandId shorthand_id = shorthand_map->GetId(property_name);
  202. if (shorthand_id != ShorthandId::Invalid)
  203. return ParseShorthandDeclaration(dictionary, shorthand_id, property_value);
  204. return false;
  205. }
  206. bool PropertySpecification::ParsePropertyDeclaration(PropertyDictionary& dictionary, PropertyId property_id, const String& property_value) const
  207. {
  208. // Parse as a single property.
  209. const PropertyDefinition* property_definition = GetProperty(property_id);
  210. if (!property_definition)
  211. return false;
  212. StringList property_values;
  213. ParsePropertyValues(property_values, property_value, SplitOption::None);
  214. if (property_values.empty())
  215. return false;
  216. Property new_property;
  217. if (!property_definition->ParseValue(new_property, property_values[0]))
  218. return false;
  219. dictionary.SetProperty(property_id, new_property);
  220. return true;
  221. }
  222. bool PropertySpecification::ParseShorthandDeclaration(PropertyDictionary& dictionary, ShorthandId shorthand_id, const String& property_value) const
  223. {
  224. const ShorthandDefinition* shorthand_definition = GetShorthand(shorthand_id);
  225. if (!shorthand_definition)
  226. return false;
  227. const SplitOption split_option =
  228. (shorthand_definition->type == ShorthandType::RecursiveCommaSeparated ? SplitOption::Comma : SplitOption::Whitespace);
  229. StringList property_values;
  230. ParsePropertyValues(property_values, property_value, split_option);
  231. if (property_values.empty())
  232. return false;
  233. // Handle the special behavior of the flex shorthand first, otherwise it acts like 'FallThrough'.
  234. if (shorthand_definition->type == ShorthandType::Flex && !property_values.empty())
  235. {
  236. RMLUI_ASSERT(shorthand_definition->items.size() == 3);
  237. if (property_values[0] == "none")
  238. {
  239. property_values = {"0", "0", "auto"};
  240. }
  241. else
  242. {
  243. // Default values when omitted from the 'flex' shorthand is specified here. These defaults are special
  244. // for this shorthand only, otherwise each underlying property has a different default value.
  245. const char* default_omitted_values[] = {"1", "1", "0"}; // flex-grow, flex-shrink, flex-basis
  246. Property new_property;
  247. bool result = true;
  248. for (int i = 0; i < 3; i++)
  249. {
  250. auto& item = shorthand_definition->items[i];
  251. result &= item.property_definition->ParseValue(new_property, default_omitted_values[i]);
  252. dictionary.SetProperty(item.property_id, new_property);
  253. }
  254. (void)result;
  255. RMLUI_ASSERT(result);
  256. }
  257. }
  258. // If this definition is a 'box'-style shorthand (x-top x-right x-bottom x-left) that needs replication.
  259. if (shorthand_definition->type == ShorthandType::Box && property_values.size() < 4)
  260. {
  261. // This array tells which property index each side is parsed from
  262. Array<int, 4> box_side_to_value_index = {0, 0, 0, 0};
  263. switch (property_values.size())
  264. {
  265. case 1:
  266. // Only one value is defined, so it is parsed onto all four sides.
  267. box_side_to_value_index = {0, 0, 0, 0};
  268. break;
  269. case 2:
  270. // Two values are defined, so the first one is parsed onto the top and bottom value, the second onto
  271. // the left and right.
  272. box_side_to_value_index = {0, 1, 0, 1};
  273. break;
  274. case 3:
  275. // Three values are defined, so the first is parsed into the top value, the second onto the left and
  276. // right, and the third onto the bottom.
  277. box_side_to_value_index = {0, 1, 2, 1};
  278. break;
  279. default: RMLUI_ERROR; break;
  280. }
  281. for (int i = 0; i < 4; i++)
  282. {
  283. RMLUI_ASSERT(shorthand_definition->items[i].type == ShorthandItemType::Property);
  284. Property new_property;
  285. int value_index = box_side_to_value_index[i];
  286. if (!shorthand_definition->items[i].property_definition->ParseValue(new_property, property_values[value_index]))
  287. return false;
  288. dictionary.SetProperty(shorthand_definition->items[i].property_definition->GetId(), new_property);
  289. }
  290. }
  291. else if (shorthand_definition->type == ShorthandType::RecursiveRepeat)
  292. {
  293. bool result = true;
  294. for (size_t i = 0; i < shorthand_definition->items.size(); i++)
  295. {
  296. const ShorthandItem& item = shorthand_definition->items[i];
  297. if (item.type == ShorthandItemType::Property)
  298. result &= ParsePropertyDeclaration(dictionary, item.property_id, property_value);
  299. else if (item.type == ShorthandItemType::Shorthand)
  300. result &= ParseShorthandDeclaration(dictionary, item.shorthand_id, property_value);
  301. else
  302. result = false;
  303. }
  304. if (!result)
  305. return false;
  306. }
  307. else if (shorthand_definition->type == ShorthandType::RecursiveCommaSeparated)
  308. {
  309. size_t num_optional = 0;
  310. for (auto& item : shorthand_definition->items)
  311. if (item.optional)
  312. num_optional += 1;
  313. if (property_values.size() + num_optional < shorthand_definition->items.size())
  314. {
  315. // Not enough subvalues declared.
  316. return false;
  317. }
  318. size_t subvalue_i = 0;
  319. String temp_subvalue;
  320. for (size_t i = 0; i < shorthand_definition->items.size() && subvalue_i < property_values.size(); i++)
  321. {
  322. bool result = false;
  323. const String* subvalue = &property_values[subvalue_i];
  324. const ShorthandItem& item = shorthand_definition->items[i];
  325. if (item.repeats)
  326. {
  327. property_values.erase(property_values.begin(), property_values.begin() + subvalue_i);
  328. temp_subvalue.clear();
  329. StringUtilities::JoinString(temp_subvalue, property_values);
  330. subvalue = &temp_subvalue;
  331. }
  332. if (item.type == ShorthandItemType::Property)
  333. result = ParsePropertyDeclaration(dictionary, item.property_id, *subvalue);
  334. else if (item.type == ShorthandItemType::Shorthand)
  335. result = ParseShorthandDeclaration(dictionary, item.shorthand_id, *subvalue);
  336. if (result)
  337. subvalue_i += 1;
  338. else if (item.repeats || !item.optional)
  339. return false;
  340. if (item.repeats)
  341. break;
  342. }
  343. }
  344. else
  345. {
  346. RMLUI_ASSERT(shorthand_definition->type == ShorthandType::Box || shorthand_definition->type == ShorthandType::FallThrough ||
  347. shorthand_definition->type == ShorthandType::Replicate || shorthand_definition->type == ShorthandType::Flex);
  348. // Abort over-specified shorthand values.
  349. if (property_values.size() > shorthand_definition->items.size())
  350. return false;
  351. size_t value_index = 0;
  352. size_t property_index = 0;
  353. for (; value_index < property_values.size() && property_index < shorthand_definition->items.size(); property_index++)
  354. {
  355. Property new_property;
  356. if (!shorthand_definition->items[property_index].property_definition->ParseValue(new_property, property_values[value_index]))
  357. {
  358. // This definition failed to parse; if we're falling through, try the next property. If there is no
  359. // next property, then abort!
  360. if (shorthand_definition->type == ShorthandType::FallThrough || shorthand_definition->type == ShorthandType::Flex)
  361. {
  362. if (property_index + 1 < shorthand_definition->items.size())
  363. continue;
  364. }
  365. return false;
  366. }
  367. dictionary.SetProperty(shorthand_definition->items[property_index].property_id, new_property);
  368. // Increment the value index, unless we're replicating the last value and we're up to the last value.
  369. if (shorthand_definition->type != ShorthandType::Replicate || value_index < property_values.size() - 1)
  370. value_index++;
  371. }
  372. // Abort if we still have values left to parse but no more properties to pass them to.
  373. if (shorthand_definition->type != ShorthandType::Replicate && value_index < property_values.size() &&
  374. property_index >= shorthand_definition->items.size())
  375. return false;
  376. }
  377. return true;
  378. }
  379. void PropertySpecification::SetPropertyDefaults(PropertyDictionary& dictionary) const
  380. {
  381. for (const auto& property : properties)
  382. {
  383. if (property && dictionary.GetProperty(property->GetId()) == nullptr)
  384. dictionary.SetProperty(property->GetId(), *property->GetDefaultValue());
  385. }
  386. }
  387. String PropertySpecification::PropertiesToString(const PropertyDictionary& dictionary, bool include_name, char delimiter) const
  388. {
  389. const PropertyMap& properties = dictionary.GetProperties();
  390. // For determinism we print the strings in order of increasing property ids.
  391. Vector<PropertyId> ids;
  392. ids.reserve(properties.size());
  393. for (auto& pair : properties)
  394. ids.push_back(pair.first);
  395. std::sort(ids.begin(), ids.end());
  396. String result;
  397. for (PropertyId id : ids)
  398. {
  399. const Property& p = properties.find(id)->second;
  400. if (include_name)
  401. result += property_map->GetName(id) + ": ";
  402. result += p.ToString() + delimiter;
  403. }
  404. if (!result.empty())
  405. result.pop_back();
  406. return result;
  407. }
  408. void PropertySpecification::ParsePropertyValues(StringList& values_list, const String& values, const SplitOption split_option) const
  409. {
  410. RMLUI_ASSERT(values_list.empty());
  411. const bool split_values = (split_option != SplitOption::None);
  412. const bool split_by_comma = (split_option == SplitOption::Comma);
  413. const bool split_by_whitespace = (split_option == SplitOption::Whitespace);
  414. String value;
  415. auto SubmitExactValue = [&]() {
  416. values_list.push_back(std::move(value));
  417. value.clear();
  418. };
  419. auto SubmitValue = [&]() {
  420. value = StringUtilities::StripWhitespace(value);
  421. if (!value.empty())
  422. SubmitExactValue();
  423. };
  424. auto IsAllWhitespace = [](const String& string) { return std::all_of(string.begin(), string.end(), StringUtilities::IsWhitespace); };
  425. auto Error = [&]() { values_list.clear(); };
  426. enum ParseState { VALUE, VALUE_PARENTHESIS, VALUE_QUOTE, VALUE_QUOTE_ESCAPE_NEXT };
  427. ParseState state = VALUE;
  428. int open_parentheses = 0;
  429. char open_quote_character = 0;
  430. size_t character_index = 0;
  431. while (character_index < values.size())
  432. {
  433. const char character = values[character_index];
  434. character_index++;
  435. switch (state)
  436. {
  437. case VALUE:
  438. {
  439. if (character == ';')
  440. {
  441. if (value.size() > 0)
  442. {
  443. values_list.push_back(value);
  444. value.clear();
  445. }
  446. }
  447. else if ((split_by_comma && character == ',') || (split_by_whitespace && StringUtilities::IsWhitespace(character)))
  448. {
  449. SubmitValue();
  450. }
  451. else if (character == '"' || character == '\'')
  452. {
  453. state = VALUE_QUOTE;
  454. open_quote_character = character;
  455. if (split_by_whitespace)
  456. SubmitValue();
  457. else if (split_by_comma)
  458. value += character;
  459. else if (IsAllWhitespace(value))
  460. value.clear();
  461. else
  462. return Error();
  463. }
  464. else if (character == '(')
  465. {
  466. open_parentheses = 1;
  467. value += character;
  468. state = VALUE_PARENTHESIS;
  469. }
  470. else
  471. {
  472. value += character;
  473. }
  474. }
  475. break;
  476. case VALUE_PARENTHESIS:
  477. {
  478. if (character == '(')
  479. {
  480. open_parentheses++;
  481. }
  482. else if (character == ')')
  483. {
  484. open_parentheses--;
  485. if (open_parentheses == 0)
  486. state = VALUE;
  487. }
  488. else if (character == '"' || character == '\'')
  489. {
  490. state = VALUE_QUOTE;
  491. open_quote_character = character;
  492. }
  493. value += character;
  494. }
  495. break;
  496. case VALUE_QUOTE:
  497. {
  498. if (character == open_quote_character)
  499. {
  500. if (open_parentheses == 0)
  501. {
  502. state = VALUE;
  503. if (split_by_comma)
  504. value += character;
  505. else
  506. SubmitExactValue();
  507. }
  508. else
  509. {
  510. state = VALUE_PARENTHESIS;
  511. value += character;
  512. }
  513. }
  514. else if (character == '\\')
  515. {
  516. state = VALUE_QUOTE_ESCAPE_NEXT;
  517. }
  518. else
  519. {
  520. value += character;
  521. }
  522. }
  523. break;
  524. case VALUE_QUOTE_ESCAPE_NEXT:
  525. {
  526. if (character == '"' || character == '\'' || character == '\\')
  527. {
  528. value += character;
  529. }
  530. else
  531. {
  532. value += '\\';
  533. value += character;
  534. }
  535. state = VALUE_QUOTE;
  536. }
  537. break;
  538. }
  539. }
  540. if (state == VALUE)
  541. SubmitValue();
  542. if (!split_values && values_list.size() > 1)
  543. return Error();
  544. }
  545. } // namespace Rml