ElementTextDefault.cpp 19 KB

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