ElementTextDefault.cpp 18 KB

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