ElementText.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  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/ElementText.h"
  29. #include "../../Include/RmlUi/Core/Context.h"
  30. #include "../../Include/RmlUi/Core/Core.h"
  31. #include "../../Include/RmlUi/Core/ElementDocument.h"
  32. #include "../../Include/RmlUi/Core/ElementUtilities.h"
  33. #include "../../Include/RmlUi/Core/Event.h"
  34. #include "../../Include/RmlUi/Core/FontEngineInterface.h"
  35. #include "../../Include/RmlUi/Core/MeshUtilities.h"
  36. #include "../../Include/RmlUi/Core/Profiling.h"
  37. #include "../../Include/RmlUi/Core/Property.h"
  38. #include "../../Include/RmlUi/Core/RenderManager.h"
  39. #include "../../Include/RmlUi/Core/TextShapingContext.h"
  40. #include "ComputeProperty.h"
  41. #include "ElementDefinition.h"
  42. #include "ElementStyle.h"
  43. #include "TransformState.h"
  44. #include <limits>
  45. namespace Rml {
  46. static bool BuildToken(String& token, const char*& token_begin, const char* string_end, bool first_token, bool collapse_white_space,
  47. bool break_at_endline, Style::TextTransform text_transformation, bool decode_escape_characters);
  48. static bool LastToken(const char* token_begin, const char* string_end, bool collapse_white_space, bool break_at_endline);
  49. static int RoundDownToIntegerClamped(float value)
  50. {
  51. constexpr int clamp = (1 << std::numeric_limits<float>::digits);
  52. constexpr float clamp_f = float{clamp};
  53. if (value >= clamp_f)
  54. return clamp;
  55. if (value <= -clamp_f)
  56. return -clamp;
  57. return static_cast<int>(value);
  58. }
  59. struct TextOverflowResolved {
  60. bool enabled = false;
  61. float overflow_width = 0.f;
  62. String overflow_text;
  63. };
  64. static TextOverflowResolved ResolveTextOverflow(Element* parent, FontFaceHandle font_face_handle)
  65. {
  66. if (!parent)
  67. return {};
  68. const auto& parent_computed = parent->GetComputedValues();
  69. if (parent_computed.overflow_x() == Style::Overflow::Visible && parent_computed.overflow_y() == Style::Overflow::Visible)
  70. return {};
  71. const Style::TextOverflow text_overflow = parent_computed.text_overflow();
  72. if (text_overflow == Style::TextOverflow::Clip)
  73. return {};
  74. const Box& box = parent->GetBox();
  75. const BoxArea clip_area = parent->GetClipArea();
  76. auto AccumulateRightSideEdgesUpTo = [](const Box& box, BoxArea up_to_area) -> float {
  77. float result = 0;
  78. for (int i = (int)up_to_area; i < int(BoxArea::Content); i++)
  79. result += box.GetEdge((BoxArea)i, BoxEdge::Right);
  80. return result;
  81. };
  82. const float overflow_width = parent->GetScrollLeft() + box.GetSize().x + AccumulateRightSideEdgesUpTo(box, clip_area);
  83. constexpr char ellipsis_chars[] = "\xE2\x80\xA6"; // U+2026
  84. constexpr char dots_chars[] = "...";
  85. String overflow_text = (text_overflow == Style::TextOverflow::String
  86. ? parent->GetComputedValues().text_overflow_string()
  87. : (GetFontEngineInterface()->GetFontMetrics(font_face_handle).has_ellipsis ? ellipsis_chars : dots_chars));
  88. return TextOverflowResolved{
  89. true,
  90. overflow_width,
  91. std::move(overflow_text),
  92. };
  93. }
  94. void LogMissingFontFace(Element* element)
  95. {
  96. const String font_family_property = element->GetProperty<String>("font-family");
  97. if (font_family_property.empty())
  98. {
  99. Log::Message(Log::LT_WARNING, "No font face defined. Missing 'font-family' property. On element %s", element->GetAddress().c_str());
  100. }
  101. else
  102. {
  103. const ComputedValues& computed = element->GetComputedValues();
  104. const String font_face_description = GetFontFaceDescription(font_family_property, computed.font_style(), computed.font_weight());
  105. Log::Message(Log::LT_WARNING,
  106. "No font face defined. Ensure (1) that Context::Update is run after new elements are constructed, before Context::Render, "
  107. "and (2) that the specified font face %s has been successfully loaded. "
  108. "Please see previous log messages for all successfully loaded fonts. On element %s",
  109. font_face_description.c_str(), element->GetAddress().c_str());
  110. }
  111. }
  112. ElementText::ElementText() :
  113. Node(), colour(255, 255, 255), opacity(1), font_handle_version(0), geometry_dirty(true), dirty_layout_on_change(true),
  114. generated_decoration(Style::TextDecoration::None), decoration_property(Style::TextDecoration::None), font_effects_dirty(true),
  115. font_effects_handle(0)
  116. {}
  117. ElementText::~ElementText() {}
  118. void ElementText::SetText(const String& _text)
  119. {
  120. if (text != _text)
  121. {
  122. text = _text;
  123. if (dirty_layout_on_change)
  124. DirtyLayout();
  125. }
  126. }
  127. const String& ElementText::GetText() const
  128. {
  129. return text;
  130. }
  131. void ElementText::Render(Element* parent, Vector2f translation)
  132. {
  133. RMLUI_ZoneScoped;
  134. RMLUI_ASSERT(parent);
  135. FontFaceHandle font_face_handle = parent->GetFontFaceHandle();
  136. if (font_face_handle == 0)
  137. return;
  138. RenderManager& render_manager = GetContext()->GetRenderManager();
  139. // If our font effects have potentially changed, update it and force a geometry generation if necessary.
  140. if (font_effects_dirty && UpdateFontEffects())
  141. geometry_dirty = true;
  142. // Dirty geometry if font version has changed.
  143. int new_version = GetFontEngineInterface()->GetVersion(font_face_handle);
  144. if (new_version != font_handle_version)
  145. {
  146. font_handle_version = new_version;
  147. geometry_dirty = true;
  148. }
  149. // Regenerate the geometry if the colour or font configuration has altered.
  150. if (geometry_dirty)
  151. GenerateGeometry(render_manager, font_face_handle);
  152. // Regenerate text decoration if necessary.
  153. if (decoration_property != generated_decoration)
  154. {
  155. if (decoration_property == Style::TextDecoration::None)
  156. {
  157. decoration.reset();
  158. }
  159. else
  160. {
  161. Mesh mesh;
  162. if (decoration)
  163. mesh = decoration->Release(Geometry::ReleaseMode::ClearMesh);
  164. else
  165. decoration = MakeUnique<Geometry>();
  166. GenerateDecoration(mesh, font_face_handle);
  167. *decoration = GetRenderManager()->MakeGeometry(std::move(mesh));
  168. }
  169. generated_decoration = decoration_property;
  170. }
  171. bool render = true;
  172. // Do a visibility test against the scissor region to avoid unnecessary render calls. Instead of handling
  173. // culling in complicated transform cases, for simplicity we always proceed to render if one is detected.
  174. Rectanglei scissor_region = render_manager.GetScissorRegion();
  175. if (!scissor_region.Valid())
  176. scissor_region = Rectanglei::FromSize(render_manager.GetViewport());
  177. if (!parent->GetTransformState() || !parent->GetTransformState()->GetTransform())
  178. {
  179. const FontMetrics& font_metrics = GetFontEngineInterface()->GetFontMetrics(parent->GetFontFaceHandle());
  180. const int ascent = Math::RoundUpToInteger(font_metrics.ascent);
  181. const int descent = Math::RoundUpToInteger(font_metrics.descent);
  182. render = false;
  183. for (const Line& line : lines)
  184. {
  185. const Vector2i baseline = Vector2i(translation + line.position);
  186. const Rectanglei line_region = Rectanglei::FromCorners(baseline - Vector2i(0, ascent), baseline + Vector2i(line.width, descent));
  187. if (line_region.Valid() && scissor_region.Intersects(line_region))
  188. {
  189. render = true;
  190. break;
  191. }
  192. }
  193. }
  194. if (render)
  195. {
  196. for (size_t i = 0; i < geometry.size(); ++i)
  197. geometry[i].geometry.Render(translation, geometry[i].texture);
  198. }
  199. if (decoration)
  200. decoration->Render(translation);
  201. }
  202. bool ElementText::GenerateLine(String& line, int& line_length, float& line_width, int line_begin, float maximum_line_width, float right_spacing_width,
  203. bool trim_whitespace_prefix, bool decode_escape_characters, bool allow_empty)
  204. {
  205. RMLUI_ZoneScoped;
  206. RMLUI_ASSERT(maximum_line_width >= 0.f);
  207. Element* parent = GetParentElement();
  208. RMLUI_ASSERT(parent);
  209. FontFaceHandle font_face_handle = parent->GetFontFaceHandle();
  210. // Initialise the output variables.
  211. line.clear();
  212. line_length = 0;
  213. line_width = 0;
  214. // Bail if we don't have a valid font face.
  215. if (font_face_handle == 0)
  216. {
  217. LogMissingFontFace(parent);
  218. return true;
  219. }
  220. // Determine how we are processing white-space while formatting the text.
  221. using namespace Style;
  222. const auto& computed = parent->GetComputedValues();
  223. const WhiteSpace white_space_property = computed.white_space();
  224. const bool collapse_white_space =
  225. (white_space_property == WhiteSpace::Normal || white_space_property == WhiteSpace::Nowrap || white_space_property == WhiteSpace::Preline);
  226. const bool break_at_line =
  227. (white_space_property == WhiteSpace::Normal || white_space_property == WhiteSpace::Prewrap || white_space_property == WhiteSpace::Preline);
  228. const bool break_at_endline =
  229. (white_space_property == WhiteSpace::Pre || white_space_property == WhiteSpace::Prewrap || white_space_property == WhiteSpace::Preline);
  230. const TextShapingContext text_shaping_context{computed.language(), computed.direction(), computed.font_kerning(), computed.letter_spacing()};
  231. TextTransform text_transform_property = computed.text_transform();
  232. WordBreak word_break = computed.word_break();
  233. FontEngineInterface* font_engine_interface = GetFontEngineInterface();
  234. // Starting at the line_begin character, we generate sections of the text (we'll call them tokens) depending on the
  235. // white-space parsing parameters. Each section is then appended to the line if it can fit. If not, or if an
  236. // endline is found (and we're processing them), then the line is ended. kthxbai!
  237. const char* token_begin = text.c_str() + line_begin;
  238. const char* string_end = text.c_str() + text.size();
  239. while (token_begin != string_end)
  240. {
  241. String token;
  242. const char* next_token_begin = token_begin;
  243. Character previous_codepoint = Character::Null;
  244. if (!line.empty())
  245. previous_codepoint =
  246. StringUtilities::ToCharacter(StringUtilities::SeekBackwardUTF8(&line.back(), line.data()), line.data() + line.size());
  247. // Generate the next token and determine its pixel-length.
  248. bool break_line = BuildToken(token, next_token_begin, string_end, line.empty() && trim_whitespace_prefix, collapse_white_space,
  249. break_at_endline, text_transform_property, decode_escape_characters);
  250. int token_width = font_engine_interface->GetStringWidth(font_face_handle, token, text_shaping_context, previous_codepoint);
  251. // If we're breaking to fit a line box, check if the token can fit on the line before we add it.
  252. if (break_at_line)
  253. {
  254. const bool is_last_token = LastToken(next_token_begin, string_end, collapse_white_space, break_at_endline);
  255. int max_token_width = RoundDownToIntegerClamped(maximum_line_width - (is_last_token ? line_width + right_spacing_width : line_width));
  256. if (token_width > max_token_width)
  257. {
  258. if (word_break == WordBreak::BreakAll || (word_break == WordBreak::BreakWord && line.empty()))
  259. {
  260. // Try to break up the word
  261. max_token_width = RoundDownToIntegerClamped(maximum_line_width - line_width);
  262. const int token_max_size = int(next_token_begin - token_begin);
  263. const char* partial_string_end = token_begin + token_max_size;
  264. // @performance: Can be made much faster. Use string width heuristics and logarithmic search.
  265. while (true)
  266. {
  267. partial_string_end = StringUtilities::SeekBackwardUTF8(partial_string_end - 1, token_begin);
  268. bool force_loop_break_at_end = false;
  269. if (partial_string_end == token_begin)
  270. {
  271. // Not even the first character of the token fits. Let it overflow onto the next line if we can.
  272. if (allow_empty || !line.empty())
  273. return false;
  274. // Continue by forcing the first character to be consumed, even though it will overflow.
  275. partial_string_end = StringUtilities::SeekForwardUTF8(token_begin + 1, token_begin + token_max_size);
  276. force_loop_break_at_end = true;
  277. }
  278. token.clear();
  279. next_token_begin = token_begin;
  280. BuildToken(token, next_token_begin, partial_string_end, line.empty() && trim_whitespace_prefix, collapse_white_space,
  281. break_at_endline, text_transform_property, decode_escape_characters);
  282. token_width = font_engine_interface->GetStringWidth(font_face_handle, token, text_shaping_context, previous_codepoint);
  283. if (force_loop_break_at_end || token_width <= max_token_width)
  284. break;
  285. }
  286. break_line = true;
  287. }
  288. else if (allow_empty || !line.empty())
  289. {
  290. // Let the token overflow into the next line.
  291. return false;
  292. }
  293. }
  294. }
  295. // The token can fit on the end of the line, so add it onto the end and increment our width and length counters.
  296. line += token;
  297. line_length += (int)(next_token_begin - token_begin);
  298. line_width += token_width;
  299. // Break out of the loop if an endline was forced.
  300. if (break_line && (allow_empty || !line.empty()))
  301. return false;
  302. // Set the beginning of the next token.
  303. token_begin = next_token_begin;
  304. }
  305. return true;
  306. }
  307. void ElementText::ClearLines()
  308. {
  309. RMLUI_ZoneScoped;
  310. lines.clear();
  311. generated_decoration = Style::TextDecoration::None;
  312. geometry_dirty = true;
  313. }
  314. void ElementText::AddLine(Vector2f line_position, String line)
  315. {
  316. if (font_effects_dirty)
  317. UpdateFontEffects();
  318. lines.emplace_back(std::move(line), line_position);
  319. geometry_dirty = true;
  320. }
  321. void ElementText::SuppressAutoLayout()
  322. {
  323. dirty_layout_on_change = false;
  324. }
  325. void ElementText::OverrideColour(Optional<Colourb> new_override_colour)
  326. {
  327. override_colour = new_override_colour;
  328. geometry_dirty = true;
  329. generated_decoration = Style::TextDecoration::None;
  330. }
  331. const ComputedValues& ElementText::GetComputedValues() const
  332. {
  333. Element* parent_element = GetParentElement();
  334. RMLUI_ASSERT(parent_element);
  335. return parent_element->GetComputedValues();
  336. }
  337. void ElementText::OnParentPropertyChange(Element* parent, const PropertyIdSet& changed_properties)
  338. {
  339. RMLUI_ZoneScoped;
  340. RMLUI_ASSERT(parent);
  341. bool colour_changed = false;
  342. bool font_face_changed = false;
  343. auto& computed = parent->GetComputedValues();
  344. if (changed_properties.Contains(PropertyId::Color) || changed_properties.Contains(PropertyId::Opacity))
  345. {
  346. const float new_opacity = computed.opacity();
  347. const bool opacity_changed = opacity != new_opacity;
  348. ColourbPremultiplied new_colour = override_colour.value_or(computed.color()).ToPremultiplied(new_opacity);
  349. colour_changed = colour != new_colour;
  350. if (colour_changed)
  351. {
  352. colour = new_colour;
  353. }
  354. if (opacity_changed)
  355. {
  356. opacity = new_opacity;
  357. font_effects_dirty = true;
  358. geometry_dirty = true;
  359. }
  360. }
  361. if (changed_properties.Contains(PropertyId::FontFamily) || //
  362. changed_properties.Contains(PropertyId::FontWeight) || //
  363. changed_properties.Contains(PropertyId::FontStyle) || //
  364. changed_properties.Contains(PropertyId::FontSize) || //
  365. changed_properties.Contains(PropertyId::FontKerning) || //
  366. changed_properties.Contains(PropertyId::LetterSpacing) || //
  367. changed_properties.Contains(PropertyId::RmlUi_Language) || //
  368. changed_properties.Contains(PropertyId::RmlUi_Direction) || //
  369. changed_properties.Contains(PropertyId::TextOverflow))
  370. {
  371. font_face_changed = true;
  372. geometry_dirty = true;
  373. font_effects_handle = 0;
  374. font_effects_dirty = true;
  375. font_handle_version = 0;
  376. }
  377. if (changed_properties.Contains(PropertyId::FontEffect))
  378. {
  379. font_effects_dirty = true;
  380. }
  381. if (changed_properties.Contains(PropertyId::TextDecoration))
  382. {
  383. decoration_property = computed.text_decoration();
  384. if (decoration && decoration_property == Style::TextDecoration::None)
  385. decoration.reset();
  386. }
  387. if (font_face_changed)
  388. {
  389. // We have to let our document know we need to be regenerated.
  390. if (dirty_layout_on_change)
  391. DirtyLayout();
  392. }
  393. else if (colour_changed)
  394. {
  395. // Force the geometry to be regenerated.
  396. geometry_dirty = true;
  397. // Re-colour the decoration geometry.
  398. if (decoration)
  399. {
  400. Mesh mesh = decoration->Release();
  401. for (Vertex& vertex : mesh.vertices)
  402. vertex.colour = colour;
  403. if (RenderManager* render_manager = GetRenderManager())
  404. *decoration = render_manager->MakeGeometry(std::move(mesh));
  405. }
  406. }
  407. }
  408. bool ElementText::UpdateFontEffects()
  409. {
  410. RMLUI_ZoneScoped;
  411. Element* parent = GetParentElement();
  412. RMLUI_ASSERT(parent);
  413. if (parent->GetFontFaceHandle() == 0)
  414. return false;
  415. font_effects_dirty = false;
  416. static const FontEffectList empty_font_effects;
  417. // Fetch the font-effect for this text element
  418. const FontEffectList* font_effects = &empty_font_effects;
  419. if (parent->GetComputedValues().has_font_effect())
  420. {
  421. if (const Property* p = parent->GetProperty(PropertyId::FontEffect))
  422. if (FontEffectsPtr effects = p->Get<FontEffectsPtr>())
  423. font_effects = &effects->list;
  424. }
  425. // Request a font layer configuration to match this set of effects. If this is different from
  426. // our old configuration, then return true to indicate we'll need to regenerate geometry.
  427. FontEffectsHandle new_font_effects_handle = GetFontEngineInterface()->PrepareFontEffects(parent->GetFontFaceHandle(), *font_effects);
  428. if (new_font_effects_handle != font_effects_handle)
  429. {
  430. font_effects_handle = new_font_effects_handle;
  431. return true;
  432. }
  433. return false;
  434. }
  435. void ElementText::GenerateGeometry(RenderManager& render_manager, const FontFaceHandle font_face_handle)
  436. {
  437. RMLUI_ZoneScopedC(0xD2691E);
  438. Element* parent = GetParentElement();
  439. RMLUI_ASSERT(parent);
  440. const TextOverflowResolved text_overflow = ResolveTextOverflow(parent, font_face_handle);
  441. const auto& computed = parent->GetComputedValues();
  442. const TextShapingContext text_shaping_context{computed.language(), computed.direction(), computed.font_kerning(), computed.letter_spacing()};
  443. TexturedMeshList mesh_list;
  444. mesh_list.reserve(geometry.size());
  445. for (Line& line : lines)
  446. {
  447. line.width = GetFontEngineInterface()->GenerateString(render_manager, font_face_handle, font_effects_handle, line.text, line.position, colour,
  448. opacity, text_shaping_context, mesh_list);
  449. }
  450. const auto text_overflows_on_line = [&](const Line& line) { return line.position.x + line.width > text_overflow.overflow_width; };
  451. if (text_overflow.enabled && std::any_of(lines.begin(), lines.end(), text_overflows_on_line))
  452. {
  453. mesh_list.clear();
  454. for (Line& line : lines)
  455. {
  456. if (line.text.empty())
  457. continue;
  458. String abbreviated_text;
  459. StringView text_submit_view = line.text;
  460. StringIteratorU8 view(line.text, line.text.size());
  461. --view;
  462. // If we have text overflow, reduce the string one character at a time, append the ellipsis or custom
  463. // string, and try again until it fits. @performance Can be improved by e.g. logarithmic search. Consider
  464. // combining it with the word-breaking algorithm of 'GenerateLine'.
  465. for (; text_overflows_on_line(line) && view && view.get() != line.text.c_str(); --view)
  466. {
  467. abbreviated_text.reserve(line.text.size() + text_overflow.overflow_text.size());
  468. abbreviated_text.assign(line.text.c_str(), view.get());
  469. abbreviated_text.append(text_overflow.overflow_text);
  470. line.width = GetFontEngineInterface()->GetStringWidth(font_face_handle, abbreviated_text, text_shaping_context);
  471. text_submit_view = abbreviated_text;
  472. }
  473. line.width = GetFontEngineInterface()->GenerateString(render_manager, font_face_handle, font_effects_handle, text_submit_view,
  474. line.position, colour, opacity, text_shaping_context, mesh_list);
  475. }
  476. }
  477. // Apply the new geometry and textures. Reuse the old geometry if the mesh matches, which can be relatively common
  478. // where the layout is changed in a way that does not visually affect this element.
  479. geometry.resize(mesh_list.size());
  480. for (size_t i = 0; i < mesh_list.size(); i++)
  481. {
  482. if (!geometry[i].geometry || geometry[i].geometry.GetMesh() != mesh_list[i].mesh)
  483. geometry[i].geometry = render_manager.MakeGeometry(std::move(mesh_list[i].mesh));
  484. geometry[i].texture = mesh_list[i].texture;
  485. }
  486. generated_decoration = Style::TextDecoration::None;
  487. geometry_dirty = false;
  488. }
  489. void ElementText::GenerateDecoration(Mesh& mesh, const FontFaceHandle font_face_handle)
  490. {
  491. RMLUI_ZoneScopedC(0xA52A2A);
  492. RMLUI_ASSERT(decoration);
  493. const FontMetrics& metrics = GetFontEngineInterface()->GetFontMetrics(font_face_handle);
  494. float offset = 0.f;
  495. switch (decoration_property)
  496. {
  497. case Style::TextDecoration::Underline: offset = metrics.underline_position; break;
  498. case Style::TextDecoration::Overline: offset = -1.1f * metrics.ascent; break;
  499. case Style::TextDecoration::LineThrough: offset = -0.65f * metrics.x_height; break;
  500. case Style::TextDecoration::None: return;
  501. }
  502. for (const Line& line : lines)
  503. {
  504. const Vector2f position = {line.position.x, line.position.y + offset};
  505. const Vector2f size = {(float)line.width, metrics.underline_thickness};
  506. MeshUtilities::GenerateLine(mesh, position, size, colour);
  507. }
  508. }
  509. static bool BuildToken(String& token, const char*& token_begin, const char* string_end, bool first_token, bool collapse_white_space,
  510. bool break_at_endline, Style::TextTransform text_transformation, bool decode_escape_characters)
  511. {
  512. RMLUI_ASSERT(token_begin != string_end);
  513. token.reserve(string_end - token_begin + token.size());
  514. // Check what the first character of the token is; all we need to know is if it is white-space or not.
  515. bool parsing_white_space = StringUtilities::IsWhitespace(*token_begin);
  516. // Loop through the string from the token's beginning until we find an end to the token. This can occur in various
  517. // places, depending on the white-space processing;
  518. // - at the end of a section of non-white-space characters,
  519. // - at the end of a section of white-space characters, if we're not collapsing white-space,
  520. // - at an endline token, if we're breaking on endlines.
  521. while (token_begin != string_end)
  522. {
  523. bool force_non_whitespace = false;
  524. char character = *token_begin;
  525. const char* escape_begin = token_begin;
  526. // Check for an ampersand; if we find one, we've got an HTML escaped character.
  527. if (decode_escape_characters && character == '&')
  528. {
  529. // Find the terminating ';'.
  530. while (token_begin != string_end && *token_begin != ';')
  531. ++token_begin;
  532. // If we couldn't find the ';', print the token like normal text.
  533. if (token_begin == string_end)
  534. {
  535. token_begin = escape_begin;
  536. }
  537. // We could find a ';', parse the escape code. If the escape code is recognised, set the parsed character
  538. // to the appropriate one. If it is a non-breaking space, prevent it being picked up as whitespace. If it
  539. // is not recognised, print the token like normal text.
  540. else
  541. {
  542. String escape_code(escape_begin + 1, token_begin);
  543. if (escape_code == "lt")
  544. character = '<';
  545. else if (escape_code == "gt")
  546. character = '>';
  547. else if (escape_code == "amp")
  548. character = '&';
  549. else if (escape_code == "quot")
  550. character = '"';
  551. else if (escape_code == "nbsp")
  552. {
  553. character = ' ';
  554. force_non_whitespace = true;
  555. }
  556. else
  557. token_begin = escape_begin;
  558. }
  559. }
  560. // Check for an endline token; if we're breaking on endlines and we find one, then return true to indicate a
  561. // forced break.
  562. if (break_at_endline && character == '\n')
  563. {
  564. token += '\n';
  565. token_begin++;
  566. return true;
  567. }
  568. // If we've transitioned from white-space characters to non-white-space characters, or vice-versa, then check
  569. // if should terminate the token; if we're not collapsing white-space, then yes (as sections of white-space are
  570. // non-breaking), otherwise only if we've transitioned from characters to white-space.
  571. bool white_space = !force_non_whitespace && StringUtilities::IsWhitespace(character);
  572. if (white_space != parsing_white_space)
  573. {
  574. if (!collapse_white_space)
  575. {
  576. // Restore pointer to the beginning of the escaped token, if we processed an escape code.
  577. token_begin = escape_begin;
  578. return false;
  579. }
  580. // We're collapsing white-space; we only tokenise words, not white-space, so we're only done tokenising
  581. // once we've begun parsing non-white-space and then found white-space.
  582. if (!parsing_white_space)
  583. {
  584. // However, if we are the last non-whitespace character in the string, and there are trailing
  585. // whitespace characters after this token, then we need to append a single space to the end of this
  586. // token.
  587. if (token_begin != string_end && LastToken(token_begin, string_end, collapse_white_space, break_at_endline))
  588. token += ' ';
  589. return false;
  590. }
  591. // We've transitioned from white-space to non-white-space, so we append a single white-space character.
  592. if (!first_token)
  593. token += ' ';
  594. parsing_white_space = false;
  595. }
  596. // If the current character is white-space, we'll append a space character to the token if we're not collapsing
  597. // sections of white-space.
  598. if (white_space)
  599. {
  600. if (!collapse_white_space)
  601. token += ' ';
  602. }
  603. else
  604. {
  605. if (text_transformation == Style::TextTransform::Uppercase)
  606. {
  607. if (character >= 'a' && character <= 'z')
  608. character += ('A' - 'a');
  609. }
  610. else if (text_transformation == Style::TextTransform::Lowercase)
  611. {
  612. if (character >= 'A' && character <= 'Z')
  613. character -= ('A' - 'a');
  614. }
  615. token += character;
  616. }
  617. ++token_begin;
  618. }
  619. return false;
  620. }
  621. static bool LastToken(const char* token_begin, const char* string_end, bool collapse_white_space, bool break_at_endline)
  622. {
  623. bool last_token = (token_begin == string_end);
  624. if (collapse_white_space && !last_token)
  625. {
  626. last_token = true;
  627. const char* character = token_begin;
  628. while (character != string_end)
  629. {
  630. if (!StringUtilities::IsWhitespace(*character) || (break_at_endline && *character == '\n'))
  631. {
  632. last_token = false;
  633. break;
  634. }
  635. character++;
  636. }
  637. }
  638. return last_token;
  639. }
  640. } // namespace Rml