ElementTextDefault.cpp 19 KB

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