ElementTextDefault.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. /*
  2. * This source file is part of RmlUi, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://github.com/mikke89/RmlUi
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. * Copyright (c) 2019 The RmlUi Team, and contributors
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. */
  28. #include "ElementTextDefault.h"
  29. #include "ElementDefinition.h"
  30. #include "ElementStyle.h"
  31. #include "../../Include/RmlUi/Core/Core.h"
  32. #include "../../Include/RmlUi/Core/Context.h"
  33. #include "../../Include/RmlUi/Core/ElementDocument.h"
  34. #include "../../Include/RmlUi/Core/ElementUtilities.h"
  35. #include "../../Include/RmlUi/Core/Event.h"
  36. #include "../../Include/RmlUi/Core/FontEngineInterface.h"
  37. #include "../../Include/RmlUi/Core/GeometryUtilities.h"
  38. #include "../../Include/RmlUi/Core/Property.h"
  39. #include "../../Include/RmlUi/Core/Profiling.h"
  40. namespace Rml {
  41. namespace Core {
  42. static bool BuildToken(String& token, const char*& token_begin, const char* string_end, bool first_token, bool collapse_white_space, bool break_at_endline, Style::TextTransform text_transformation, bool decode_escape_characters);
  43. static bool LastToken(const char* token_begin, const char* string_end, bool collapse_white_space, bool break_at_endline);
  44. ElementTextDefault::ElementTextDefault(const String& tag) : ElementText(tag), colour(255, 255, 255), decoration(this)
  45. {
  46. dirty_layout_on_change = true;
  47. generated_decoration = Style::TextDecoration::None;
  48. decoration_property = Style::TextDecoration::None;
  49. geometry_dirty = true;
  50. font_effects_handle = 0;
  51. font_effects_dirty = true;
  52. font_handle_version = 0;
  53. }
  54. ElementTextDefault::~ElementTextDefault()
  55. {
  56. }
  57. void ElementTextDefault::SetText(const String& _text)
  58. {
  59. if (text != _text)
  60. {
  61. text = _text;
  62. if (dirty_layout_on_change)
  63. DirtyLayout();
  64. }
  65. }
  66. const String& ElementTextDefault::GetText() const
  67. {
  68. return text;
  69. }
  70. void ElementTextDefault::OnRender()
  71. {
  72. RMLUI_ZoneScoped;
  73. FontFaceHandle font_face_handle = GetFontFaceHandle();
  74. if (font_face_handle == 0)
  75. return;
  76. // If our font effects have potentially changed, update it and force a geometry generation if necessary.
  77. if (font_effects_dirty && UpdateFontEffects())
  78. geometry_dirty = true;
  79. // Dirty geometry if font version has changed.
  80. int new_version = GetFontEngineInterface()->GetVersion(font_face_handle);
  81. if (new_version != font_handle_version)
  82. {
  83. font_handle_version = new_version;
  84. geometry_dirty = true;
  85. }
  86. // Regenerate the geometry if the colour or font configuration has altered.
  87. if (geometry_dirty)
  88. GenerateGeometry(font_face_handle);
  89. Vector2f translation = GetAbsoluteOffset();
  90. bool render = true;
  91. Vector2i clip_origin;
  92. Vector2i clip_dimensions;
  93. if (GetContext()->GetActiveClipRegion(clip_origin, clip_dimensions))
  94. {
  95. float clip_top = (float)clip_origin.y;
  96. float clip_left = (float)clip_origin.x;
  97. float clip_right = (float)(clip_origin.x + clip_dimensions.x);
  98. float clip_bottom = (float)(clip_origin.y + clip_dimensions.y);
  99. float line_height = (float)GetFontEngineInterface()->GetLineHeight(GetFontFaceHandle());
  100. render = false;
  101. for (size_t i = 0; i < lines.size(); ++i)
  102. {
  103. const Line& line = lines[i];
  104. float x = translation.x + line.position.x;
  105. float y = translation.y + line.position.y;
  106. bool render_line = !(x > clip_right);
  107. render_line = render_line && !(x + line.width < clip_left);
  108. render_line = render_line && !(y - line_height > clip_bottom);
  109. render_line = render_line && !(y < clip_top);
  110. if (render_line)
  111. {
  112. render = true;
  113. break;
  114. }
  115. }
  116. }
  117. translation = translation.Round();
  118. if (render)
  119. {
  120. for (size_t i = 0; i < geometry.size(); ++i)
  121. geometry[i].Render(translation);
  122. }
  123. if (decoration_property != Style::TextDecoration::None)
  124. decoration.Render(translation);
  125. }
  126. // Generates a token of text from this element, returning only the width.
  127. bool ElementTextDefault::GenerateToken(float& token_width, int line_begin)
  128. {
  129. RMLUI_ZoneScoped;
  130. // Bail if we don't have a valid font face.
  131. FontFaceHandle font_face_handle = GetFontFaceHandle();
  132. if (font_face_handle == 0 ||
  133. line_begin >= (int) text.size())
  134. return 0;
  135. // Determine how we are processing white-space while formatting the text.
  136. using namespace Style;
  137. auto& computed = GetComputedValues();
  138. WhiteSpace white_space_property = computed.white_space;
  139. bool collapse_white_space = white_space_property == WhiteSpace::Normal ||
  140. white_space_property == WhiteSpace::Nowrap ||
  141. white_space_property == WhiteSpace::Preline;
  142. bool break_at_endline = white_space_property == WhiteSpace::Pre ||
  143. white_space_property == WhiteSpace::Prewrap ||
  144. white_space_property == WhiteSpace::Preline;
  145. const char* token_begin = text.c_str() + line_begin;
  146. String token;
  147. BuildToken(token, token_begin, text.c_str() + text.size(), true, collapse_white_space, break_at_endline, computed.text_transform, true);
  148. token_width = (float) GetFontEngineInterface()->GetStringWidth(font_face_handle, token);
  149. return LastToken(token_begin, text.c_str() + text.size(), collapse_white_space, break_at_endline);
  150. }
  151. // Generates a line of text rendered from this element
  152. bool ElementTextDefault::GenerateLine(String& line, int& line_length, float& line_width, int line_begin, float maximum_line_width, float right_spacing_width, bool trim_whitespace_prefix, bool decode_escape_characters)
  153. {
  154. RMLUI_ZoneScoped;
  155. FontFaceHandle font_face_handle = GetFontFaceHandle();
  156. // Initialise the output variables.
  157. line.clear();
  158. line_length = 0;
  159. line_width = 0;
  160. // Bail if we don't have a valid font face.
  161. if (font_face_handle == 0)
  162. return true;
  163. // Determine how we are processing white-space while formatting the text.
  164. using namespace Style;
  165. auto& computed = GetComputedValues();
  166. WhiteSpace white_space_property = computed.white_space;
  167. bool collapse_white_space = white_space_property == WhiteSpace::Normal ||
  168. white_space_property == WhiteSpace::Nowrap ||
  169. white_space_property == WhiteSpace::Preline;
  170. bool break_at_line = maximum_line_width >= 0 &&
  171. (white_space_property == WhiteSpace::Normal ||
  172. white_space_property == WhiteSpace::Prewrap ||
  173. white_space_property == WhiteSpace::Preline);
  174. bool break_at_endline = white_space_property == WhiteSpace::Pre ||
  175. white_space_property == WhiteSpace::Prewrap ||
  176. white_space_property == WhiteSpace::Preline;
  177. // Determine what (if any) text transformation we are putting the characters through.
  178. TextTransform text_transform_property = computed.text_transform;
  179. // Starting at the line_begin character, we generate sections of the text (we'll call them tokens) depending on the
  180. // white-space parsing parameters. Each section is then appended to the line if it can fit. If not, or if an
  181. // endline is found (and we're processing them), then the line is ended. kthxbai!
  182. const char* token_begin = text.c_str() + line_begin;
  183. const char* string_end = text.c_str() + text.size();
  184. while (token_begin != string_end)
  185. {
  186. String token;
  187. const char* next_token_begin = token_begin;
  188. Character previous_codepoint = Character::Null;
  189. if (!line.empty())
  190. previous_codepoint = StringUtilities::ToCharacter(StringUtilities::SeekBackwardUTF8(&line.back(), line.data()));
  191. // Generate the next token and determine its pixel-length.
  192. bool break_line = BuildToken(token, next_token_begin, string_end, line.empty() && trim_whitespace_prefix, collapse_white_space, break_at_endline, text_transform_property, decode_escape_characters);
  193. int token_width = GetFontEngineInterface()->GetStringWidth(font_face_handle, token, previous_codepoint);
  194. // If we're breaking to fit a line box, check if the token can fit on the line before we add it.
  195. if (break_at_line)
  196. {
  197. if (!line.empty() &&
  198. (line_width + token_width > maximum_line_width ||
  199. (LastToken(next_token_begin, string_end, collapse_white_space, break_at_endline) && line_width + token_width > maximum_line_width - right_spacing_width)))
  200. {
  201. return false;
  202. }
  203. }
  204. // The token can fit on the end of the line, so add it onto the end and increment our width and length
  205. // counters.
  206. line += token;
  207. line_length += (int)(next_token_begin - token_begin);
  208. line_width += token_width;
  209. // Break out of the loop if an endline was forced.
  210. if (break_line)
  211. return false;
  212. // Set the beginning of the next token.
  213. token_begin = next_token_begin;
  214. }
  215. return true;
  216. }
  217. // Clears all lines of generated text and prepares the element for generating new lines.
  218. void ElementTextDefault::ClearLines()
  219. {
  220. // Clear the rendering information.
  221. for (size_t i = 0; i < geometry.size(); ++i)
  222. geometry[i].Release(true);
  223. lines.clear();
  224. decoration.Release(true);
  225. }
  226. // Adds a new line into the text element.
  227. void ElementTextDefault::AddLine(const Vector2f& line_position, const String& line)
  228. {
  229. FontFaceHandle font_face_handle = GetFontFaceHandle();
  230. if (font_face_handle == 0)
  231. return;
  232. if (font_effects_dirty)
  233. UpdateFontEffects();
  234. Vector2f baseline_position = line_position + Vector2f(0.0f, (float)GetFontEngineInterface()->GetLineHeight(font_face_handle) - GetFontEngineInterface()->GetBaseline(font_face_handle));
  235. lines.push_back(Line(line, baseline_position));
  236. geometry_dirty = true;
  237. }
  238. // Prevents the element from dirtying its document's layout when its text is changed.
  239. void ElementTextDefault::SuppressAutoLayout()
  240. {
  241. dirty_layout_on_change = false;
  242. }
  243. void ElementTextDefault::OnPropertyChange(const PropertyIdSet& changed_properties)
  244. {
  245. RMLUI_ZoneScoped;
  246. Element::OnPropertyChange(changed_properties);
  247. bool colour_changed = false;
  248. bool font_face_changed = false;
  249. auto& computed = GetComputedValues();
  250. if (changed_properties.Contains(PropertyId::Color) ||
  251. changed_properties.Contains(PropertyId::Opacity))
  252. {
  253. // Fetch our (potentially) new colour.
  254. Colourb new_colour = computed.color;
  255. float opacity = computed.opacity;
  256. new_colour.alpha = byte(opacity * float(new_colour.alpha));
  257. colour_changed = colour != new_colour;
  258. if (colour_changed)
  259. colour = new_colour;
  260. }
  261. if (changed_properties.Contains(PropertyId::FontFamily) ||
  262. changed_properties.Contains(PropertyId::FontWeight) ||
  263. changed_properties.Contains(PropertyId::FontStyle) ||
  264. changed_properties.Contains(PropertyId::FontSize))
  265. {
  266. font_face_changed = true;
  267. geometry.clear();
  268. font_effects_dirty = true;
  269. }
  270. if (changed_properties.Contains(PropertyId::TextDecoration))
  271. {
  272. decoration_property = computed.text_decoration;
  273. if (decoration_property != Style::TextDecoration::None)
  274. {
  275. if (decoration_property != generated_decoration)
  276. {
  277. decoration.Release(true);
  278. FontFaceHandle font_face_handle = GetFontFaceHandle();
  279. if (font_face_handle != 0)
  280. {
  281. for (size_t i = 0; i < lines.size(); ++i)
  282. GenerateLineDecoration(font_face_handle, lines[i]);
  283. }
  284. generated_decoration = decoration_property;
  285. }
  286. }
  287. }
  288. if (font_face_changed)
  289. {
  290. // We have to let our document know we need to be regenerated.
  291. if (dirty_layout_on_change)
  292. DirtyLayout();
  293. }
  294. else if (colour_changed)
  295. {
  296. // Force the geometry to be regenerated.
  297. geometry_dirty = true;
  298. // Re-colour the decoration geometry.
  299. std::vector< Vertex >& vertices = decoration.GetVertices();
  300. for (size_t i = 0; i < vertices.size(); ++i)
  301. vertices[i].colour = colour;
  302. decoration.Release();
  303. }
  304. }
  305. // Returns the RML of this element
  306. void ElementTextDefault::GetRML(String& content)
  307. {
  308. content += text;
  309. }
  310. // Updates the configuration this element uses for its font.
  311. bool ElementTextDefault::UpdateFontEffects()
  312. {
  313. RMLUI_ZoneScoped;
  314. if (GetFontFaceHandle() == 0)
  315. return false;
  316. font_effects_dirty = false;
  317. static const FontEffectList empty_font_effects;
  318. // Fetch the font-effect for this text element
  319. const FontEffectList* font_effects = &empty_font_effects;
  320. if (const FontEffects* effects = GetComputedValues().font_effect.get())
  321. font_effects = &effects->list;
  322. // Request a font layer configuration to match this set of effects. If this is different from
  323. // our old configuration, then return true to indicate we'll need to regenerate geometry.
  324. FontEffectsHandle new_font_effects_handle = GetFontEngineInterface()->PrepareFontEffects(GetFontFaceHandle(), *font_effects);
  325. if (new_font_effects_handle != font_effects_handle)
  326. {
  327. font_effects_handle = new_font_effects_handle;
  328. return true;
  329. }
  330. return false;
  331. }
  332. // Clears and regenerates all of the text's geometry.
  333. void ElementTextDefault::GenerateGeometry(const FontFaceHandle font_face_handle)
  334. {
  335. RMLUI_ZoneScopedC(0xD2691E);
  336. // Release the old geometry ...
  337. for (size_t i = 0; i < geometry.size(); ++i)
  338. geometry[i].Release(true);
  339. // ... and generate it all again!
  340. for (size_t i = 0; i < lines.size(); ++i)
  341. GenerateGeometry(font_face_handle, lines[i]);
  342. geometry_dirty = false;
  343. }
  344. void ElementTextDefault::GenerateGeometry(const FontFaceHandle font_face_handle, Line& line)
  345. {
  346. line.width = GetFontEngineInterface()->GenerateString(font_face_handle, font_effects_handle, line.text, line.position, colour, geometry);
  347. for (size_t i = 0; i < geometry.size(); ++i)
  348. geometry[i].SetHostElement(this);
  349. if (decoration_property != Style::TextDecoration::None)
  350. GenerateLineDecoration(font_face_handle, line);
  351. }
  352. // Generates any geometry necessary for rendering a line decoration (underline, strike-through, etc).
  353. void ElementTextDefault::GenerateLineDecoration(const FontFaceHandle font_face_handle, const Line& line)
  354. {
  355. RMLUI_ZoneScopedC(0xA52A2A);
  356. GeometryUtilities::GenerateLine(font_face_handle, &decoration, line.position, line.width, decoration_property, colour);
  357. }
  358. static bool BuildToken(String& token, const char*& token_begin, const char* string_end, bool first_token, bool collapse_white_space, bool break_at_endline, Style::TextTransform text_transformation, bool decode_escape_characters)
  359. {
  360. RMLUI_ASSERT(token_begin != string_end);
  361. token.reserve(string_end - token_begin + token.size());
  362. // Check what the first character of the token is; all we need to know is if it is white-space or not.
  363. bool parsing_white_space = StringUtilities::IsWhitespace(*token_begin);
  364. // Loop through the string from the token's beginning until we find an end to the token. This can occur in various
  365. // places, depending on the white-space processing;
  366. // - at the end of a section of non-white-space characters,
  367. // - at the end of a section of white-space characters, if we're not collapsing white-space,
  368. // - at an endline token, if we're breaking on endlines.
  369. while (token_begin != string_end)
  370. {
  371. bool force_non_whitespace = false;
  372. char character = *token_begin;
  373. const char* escape_begin = token_begin;
  374. // Check for an ampersand; if we find one, we've got an HTML escaped character.
  375. if (decode_escape_characters && character == '&')
  376. {
  377. // Find the terminating ';'.
  378. while (token_begin != string_end &&
  379. *token_begin != ';')
  380. ++token_begin;
  381. // If we couldn't find the ';', print the token like normal text.
  382. if (token_begin == string_end)
  383. {
  384. token_begin = escape_begin;
  385. }
  386. // We could find a ';', parse the escape code. If the escape code is recognised, set the parsed character
  387. // to the appropriate one. If it is a non-breaking space, prevent it being picked up as whitespace. If it
  388. // is not recognised, print the token like normal text.
  389. else
  390. {
  391. String escape_code(escape_begin + 1, token_begin);
  392. if (escape_code == "lt")
  393. character = '<';
  394. else if (escape_code == "gt")
  395. character = '>';
  396. else if (escape_code == "amp")
  397. character = '&';
  398. else if (escape_code == "quot")
  399. character = '"';
  400. else if (escape_code == "nbsp")
  401. {
  402. character = ' ';
  403. force_non_whitespace = true;
  404. }
  405. else
  406. token_begin = escape_begin;
  407. }
  408. }
  409. // Check for an endline token; if we're breaking on endlines and we find one, then return true to indicate a
  410. // forced break.
  411. if (break_at_endline &&
  412. character == '\n')
  413. {
  414. token += '\n';
  415. token_begin++;
  416. return true;
  417. }
  418. // If we've transitioned from white-space characters to non-white-space characters, or vice-versa, then check
  419. // if should terminate the token; if we're not collapsing white-space, then yes (as sections of white-space are
  420. // non-breaking), otherwise only if we've transitioned from characters to white-space.
  421. bool white_space = !force_non_whitespace && StringUtilities::IsWhitespace(character);
  422. if (white_space != parsing_white_space)
  423. {
  424. if (!collapse_white_space)
  425. {
  426. // Restore pointer to the beginning of the escaped token, if we processed an escape code.
  427. token_begin = escape_begin;
  428. return false;
  429. }
  430. // We're collapsing white-space; we only tokenise words, not white-space, so we're only done tokenising
  431. // once we've begun parsing non-white-space and then found white-space.
  432. if (!parsing_white_space)
  433. {
  434. // However, if we are the last non-whitespace character in the string, and there are trailing
  435. // whitespace characters after this token, then we need to append a single space to the end of this
  436. // token.
  437. if (token_begin != string_end &&
  438. LastToken(token_begin, string_end, collapse_white_space, break_at_endline))
  439. token += ' ';
  440. return false;
  441. }
  442. // We've transitioned from white-space to non-white-space, so we append a single white-space character.
  443. if (!first_token)
  444. token += ' ';
  445. parsing_white_space = false;
  446. }
  447. // If the current character is white-space, we'll append a space character to the token if we're not collapsing
  448. // sections of white-space.
  449. if (white_space)
  450. {
  451. if (!collapse_white_space)
  452. token += ' ';
  453. }
  454. else
  455. {
  456. if (text_transformation == Style::TextTransform::Uppercase)
  457. {
  458. if (character >= 'a' && character <= 'z')
  459. character += ('A' - 'a');
  460. }
  461. else if (text_transformation == Style::TextTransform::Lowercase)
  462. {
  463. if (character >= 'A' && character <= 'Z')
  464. character -= ('A' - 'a');
  465. }
  466. token += character;
  467. }
  468. ++token_begin;
  469. }
  470. return false;
  471. }
  472. static bool LastToken(const char* token_begin, const char* string_end, bool collapse_white_space, bool break_at_endline)
  473. {
  474. bool last_token = (token_begin == string_end);
  475. if (collapse_white_space &&
  476. !last_token)
  477. {
  478. last_token = true;
  479. const char* character = token_begin;
  480. while (character != string_end)
  481. {
  482. if (!StringUtilities::IsWhitespace(*character) ||
  483. (break_at_endline && *character == '\n'))
  484. {
  485. last_token = false;
  486. break;
  487. }
  488. character++;
  489. }
  490. }
  491. return last_token;
  492. }
  493. }
  494. }