ElementTextDefault.cpp 19 KB

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